Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java bytebuffer convert three bytes to int

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

like image 587
Tony Avatar asked Jan 14 '23 09:01

Tony


2 Answers

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.

like image 53
Cephalopod Avatar answered Jan 21 '23 17:01

Cephalopod


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.

like image 33
JDawg Avatar answered Jan 21 '23 16:01

JDawg