Skip to content
Advertisement

How do I convert a byte array to a long in Java?

I am reading 8 bytes of data in from a hardware device. I need to convert them into a numeric value. I think I want to convert them to a long as that should fit 8 bytes. I am not very familiar with Java and low level data type operations. I seem to have two problems (apart from the fact there is almost no documentation for the hardware in question), The bytes are expecting to be unsigned, so I can’t do a straight integer conversion. I am not sure what endianness they are.

Any advice would be appreciated.


Ended up with this (taken from some source code I probably should have read a week ago):

public static final long toLong (byte[] byteArray, int offset, int len)
{
   long val = 0;
   len = Math.min(len, 8);
   for (int i = (len - 1); i >= 0; i--)
   {
      val <<= 8;
      val |= (byteArray [offset + i] & 0x00FF);
   }
   return val;
}

Advertisement

Answer

For the endianness, test with some numbers you know, and then you will be using a byte shifting to move them into the long.

You may find this to be a starting point. http://www.janeg.ca/scjp/oper/shift.html

The difficulty is that depending on the endianess will change how you do it, but you will shift by 24, 16, 8 then add the last one, basically, if doing 32 bits, but you are going longer, so just do extra shifting.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement