That's because the type of msb is byte and when you shift it 32 bits to the left you get a zero (byte is just 8 bits). Change msb type to long and you should be OK.
read 5 byte and store to long
-
01-07-2022 - |
Question
I'am struggling again with type conversions in java... i need to read a 5 byte value from a ByteBuffer
and store the value in a long
.
Therefore I did this:
byte msb = b.get();
int lsb = b.getInt();
System.out.println(msb + " " + lsb);
long number = ((msb << 32)) | (((long) lsb) & 0xFFFFFFFF);
System.out.println(number);
and the log gives me the following result:
1 376263385
376263385
so msb and lsb are read correctly, but if i join them together i only get the lsb value in there. I tried to bitmask the values and tried different types to read from, but that doesnt work either.
Solution
OTHER TIPS
Try this one
long number = 0;
number = number | (((long) msb << 32));
number = number | ((lsb) & 0xFFFFFFFF);
System.out.println(number);
Remember a byte is just 8 bits long. So when you left shift the byte 32 times the 1 is lost. So you need to cast the msb to long. then do the bitmasking.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow