 # Convert Long to byte array and back

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;
buffer = (byte)value;
buffer = (byte)(value >> 8);
buffer = (byte)(value >> 16);
buffer = (byte)(value >> 24);
buffer = (byte)(value >> 32);
buffer = (byte)(value >> 40);
buffer = (byte)(value >> 48);
buffer = (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 |
buffer << 8 |
buffer << 16 |
buffer << 24 |
buffer << 32 |
buffer << 40 |
buffer << 48 |
buffer << 56);

``````

Any help would be greatly appreciated.

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

``````
value =
((long)buffer) << 0 |
((long)buffer) << 8 |
((long)buffer) << 16 |
((long)buffer) << 24 |
((long)buffer) << 32 |
((long)buffer) << 40 |
((long)buffer) << 48 |
((long)buffer) << 56;

``````

Wow, I love/hate it when the answer is so simple. Thanks a lot dacarley. My code is working now. 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;

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

``````