Convert long to char array and back I'm trying to store a state in my data logger. I can read/write fine to SD, but I can't wrap my head around reading/writing a long value correctly - I've build it down to converting it to char array and back.

My best try so far has been 

long temp = 1418172669L;
unsigned char buf[4];
buf[0] = temp         &amp; 0xFF;
buf[1] = (temp &gt;&gt;  8) &amp; 0xFF;
buf[2] = (temp &gt;&gt; 16) &amp; 0xFF;
buf[3] = (temp &gt;&gt; 24) &amp; 0xFF;

long  l = buf[0] | (buf[1] &lt;&lt; 8) | (buf[2] &lt;&lt; 16) | (buf[3] &lt;&lt; 24);


But l is very different from temp - currently the output is -26371. Am I making an obvious mistake?
I suggest using a union:

union {
    char myByte[4];
    long mylong;
} foo;


Char to Long:

Then you can just add the bytes:

foo myUnion;
myUnion.myByte[0] = buf[0];
myUnion.myByte[1] = buf[1];
myUnion.myByte[2] = buf[2];
myUnion.myByte[3] = buf[3];


Then you can access the long as:

myUnion.myLong;


Long to Char:

The same if you want to go the other way from long to char array:

foo myUnion
myUnion.myLong = 1234L;


To access bytes:

myUnion.myByte[0];
myUnion.myByte[1];
myUnion.myByte[2];
myUnion.myByte[3];