I want to store a long into a character array for writing to an SD card...and then, obviously, get it back to a long! I found the below code but the long that I get back is 722 not what I put in. Since bitwise operations make my head hurt I need help badly!
unsigned long int longInt = 1234567890;
unsigned char byteArray[4];
// convert from an unsigned long int to a 4-byte array
byteArray[0] = (int)((longInt >> 24) & 0xFF) ;
byteArray[1] = (int)((longInt >> 16) & 0xFF) ;
byteArray[2] = (int)((longInt >> 8) & 0XFF);
byteArray[3] = (int)((longInt & 0XFF));
unsigned long int anotherLongInt;
anotherLongInt = ( (byteArray[0] << 24)
+ (byteArray[1] << 16)
+ (byteArray[2] << 8)
+ (byteArray[3] ) );
AWOL: Thanks for your first answer...it is what I just stuck in my code. Is there any chance I could ask for a code example of using a union? My education in bit level operations was a VERY very VERY long time ago...
The great thing about a union is that it isn't bit-level at all - just write your variable to one part of the union, and read it back from another.
Useful tutorial
(BTW, I'm not entirely sure the solution I gave earlier is correct - bitwise OR would be better than addition, but I've a sneaking suspicion there's still a sign-extension issue lurking)