Andreas
Andreas

Reputation: 7550

How to make a Long out of two Bytes? 0x7 + 0x86 = 0x1c000

I'm trying to convert two bytes representing an unsigned integer to a Long. The bytes are in buffer which is a byte array.

// buffer[0] = 0x7 and buffer[1] = 0x86
long myLong = ( buffer[0] & 0xFF ) << 8 + ( buffer[1] & 0xFF );
Log.i("TAG",String.format("%d", myLong ); // outputs "114688" (0x1c000)
Log.i("TAG",String.format("%d + %d",
    (0xFF&buffer[0])<<8, (0xFF&buffer[1]) )); // outputs "1792 + 134"

I bitshift the high byte and then add the two bytes together. But there's some problem with the addition. I expect the first log output to give 1926, but that isn't happening. Why?

Upvotes: 0

Views: 266

Answers (1)

kiheru
kiheru

Reputation: 6618

You have an issue with operator precedence. + is evaluated before <<. (Conventionally | is used for combining).

long myLong = ((buffer[0] & 0xFF) << 8) | (buffer[1] & 0xFF)

Upvotes: 5

Related Questions