unsigned long int longInt = 1234567890; unsigned char byteArray; // convert from an unsigned long int to a 4-byte array byteArray = (int)((longInt >> 24) & 0xFF) ; byteArray = (int)((longInt >> 16) & 0xFF) ; byteArray = (int)((longInt >> 8) & 0XFF); byteArray = (int)((longInt & 0XFF)); unsigned long int anotherLongInt;
anotherLongInt = ( (byteArray << 24) + (byteArray << 16) + (byteArray << 8) + (byteArray ) );
At least until AWOL on the Arduino forum suggested the below:
anotherLongInt = ( ((unsigned long)byteArray << 24) + ((unsigned long)byteArray << 16) + ((unsigned long)byteArray << 8) + ((unsigned long)byteArray ) )
Eureka! I can now store two longs in eight bytes with a couple of distinct advantages:
- Result is fixed size which means I can seek into my file looking for specific entries
- Size on disk would generally be less than storing a string representation (unless you are only doing tiny numbers) and particularly if you wanted to do one of fixed size.
- Speedy string operations is not what you bought the Arduino for in the first place! Saving 1,000 long to char arrays took a bit more than a second while the string version (even without padding to fixed size) took more than 10 seconds.