4

I'm currently working with some little-endian binary data, and I've reached an awkward point where I'm needing to convert odd numbers of bytes into integer values.

Now using the ByteBuffer class I'm able to read ints and longs perfectly fine using the getInt() getLong() functions, which read 4 and 8 bytes respectively.

However, in this example I need to read three bytes and make an int out of them. I've tried doing getShort + get() (2 bytes + 1 byte), but I don't think that's the correct way of doing it.

I'm guessing that I'll need to bit shift the bytes together in order to get the correct int value, but I always get a bit confused over bit shifting.

Also I would have thought that the bytebuffer class would have provided a function for reading odd numbers of bytes, but it seems not.

One way of doing it would be to create a byte[] of three bytes in length, put the three bytes into that, and then wrap a bytebuffer around it, and read an int from that. But that seems like a lot of extra code.

Any suggestions or advice would be appreciated.

Thanks

3
  • Post code you´ve tried, not estimations. Please. Commented Jan 29, 2013 at 12:59
  • "I always get a bit confused over bit shifting." inhowfar? Shifting 1 bit left is like multiplying by 2, shifting right by one like dividing by 2 (and discarding the remainder). And for example you can make a byte the most significant byte (MSB) of a word by shifting the byte left 8 bits. Adding the least significant byte to the word (or ORing it in) constructs a full word from the two bytes. Commented Jan 29, 2013 at 13:02
  • 1
    Thanks TheBlastOne, that has helped to clear things in my mind! Commented Jan 29, 2013 at 13:03

2 Answers 2

6

Get three bytes via

byte[] tmp = new byte[3];
byteBuffer.get(tmp);

and convert then to int via

int i = tmp[0] << 16 | tmp[1] << 8 | tmp[2];

or

int i = tmp[2] << 16 | tmp[1] << 8 | tmp[0];

depending on your endianess.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Arian, I had a feeling I needed to do that, but now I can see it, I fully understand what it's doing. Thanks for the quick reply!
3

From the Java Language Specification:

Primitive ... byte ... values are 8-bit ... signed two's-complement integers.

To convert the byte to an "unsigned" byte, you AND it with 255. Thus, the function would be:

private static int toInt( byte[] b )
{
    return (b[0] & 255) << 16 | (b[1] & 255) << 8 | (b[2] & 255);
}

or

private static int toInt( byte[] b )
{
    return (b[2] & 255) << 16 | (b[1] & 255) << 8 | (b[0] & 255);
}

depending on your endianess.

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.