0

I would like to convert a signed int into a signed byte[] array, and later convert it back into a signed int.

However, ByteBuffers (The usual int->buffer->byte[] array) are too slow for this case.

Can this be done using basic operations?

I've seem many attempts, but I haven't seen one that works in all cases. (Usually, they fail for negative numbers.)

I am working in Java, so it is not possible to use unsigned values, even in intermediate steps.

2
  • Not sure if it will be exactly what you want but have you considered using BigInteger? It pulls the sign out of the initial value and then generated a byte[] containing the byte data of the unsigned value. Commented Jun 3, 2014 at 23:27
  • I'm curious as to how you've determined that ByteBuffer is too slow. Have you done performance tests? If so, what? Commented Jun 3, 2014 at 23:29

1 Answer 1

2
private void writeInt(int val, byte[] data, int offset) {
    data[offset    ] = (byte)(val >>> 24);
    data[offset + 1] = (byte)(val >>> 16);
    data[offset + 2] = (byte)(val >>> 8);
    data[offset + 3] = (byte)val;
}

private int readInt(byte[] data, int offset) {
    return (data[offset] << 24)
            | ((data[offset + 1] & 0xFF) << 16)
            | ((data[offset + 2] & 0xFF) << 8)
            | (data[offset + 3] & 0xFF);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.