0

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.

reox
  • 5,036
  • 11
  • 53
  • 98

2 Answers2

1

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.

Alon Catz
  • 2,417
  • 1
  • 19
  • 23
1

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.

Debobroto Das
  • 834
  • 6
  • 16