Main Site Documentation

Convert Long to byte array and back


#1

OK, all of you bit shifting experts. I’m stumped on solving a problem. I know how to convert a long to a byte array

            
long value = 12354235123;

var buffer = new byte[8];
buffer[0] = (byte)value;
buffer[1] = (byte)(value >> 8);
buffer[2] = (byte)(value >> 16);
buffer[3] = (byte)(value >> 24);
buffer[4] = (byte)(value >> 32);
buffer[5] = (byte)(value >> 40);
buffer[6] = (byte)(value >> 48);
buffer[7] = (byte)(value >> 56);

However, I’m having trouble converting the byte array back to a long. Here’s code I grabbed off the Internet which isn’t working:


long value = (buffer[0] << 0 |
                   buffer[1] << 8 |
                   buffer[2] << 16 |
                   buffer[3] << 24 |
                   buffer[4] << 32 |
                   buffer[5] << 40 |
                   buffer[6] << 48 |
                   buffer[7] << 56);

Any help would be greatly appreciated.


#2

You need to cast the bytes of the buffer back to long as you shift each one back into place:


value =
	((long)buffer[0]) << 0 |
	((long)buffer[1]) << 8 |
	((long)buffer[2]) << 16 |
	((long)buffer[3]) << 24 |
	((long)buffer[4]) << 32 |
	((long)buffer[5]) << 40 |
	((long)buffer[6]) << 48 |
	((long)buffer[7]) << 56;


#3

Wow, I love/hate it when the answer is so simple. Thanks a lot dacarley. My code is working now. :wink:


#4

Hi.
havent tested your code so i dont know what’s wrong but i figured why not iterate with a for loop, and it seems to work:



long value = 12354235123;
byte [] buffer = new byte[8];   

for(int i= 0; i < 8; i++)
{   
  buffer[7 - i] = (byte)(value >> (i * 8));   
}

long value2=0;

for (int i = 0; i < 8; i++)
{
    value2 <<= 8;
    value2 ^= (long)buffer[i] & 0xFF;
}  

// now value2 == value