in a C program I have an long* that I want to serialize (thus converting to chars). A long doesn't fit in a single char, and the size varies depending of the processor (can be 4 bytes or 8 bytes).
Theres a good way to make the serialization and de-serialization?
This is portable, but nowhere near as inefficient as using printf/scanf
void longtochar(char *buffer, unsigned long number) {
int i;
for (i=0; i<sizeof(long); i++) {
buffer[i] = number & 0xFF; // place bottom 8 bits in char
number = number >> 8; // shift down remaining bits
}
return; // the long is now stored in the first few (2,4,or 8) bytes of buffer
}
And to unpack it again (assuming long is the same size)
long chartolong(char *buffer) {
long number = 0;
int i;
for (i=sizeof(long)-1; i>=0; i--) {
number = number << 8; // left shift bits in long already
number += buffer[i]; // add in bottom 8 bits
}
return number;
}
Do note the BIG assumption that long is the same length on both systems. Safe thing to do is #include <stdint.h> and use the types it provides (uint32_t or uint16_t).
Also, my code has it as an unsigned long. I don't have access to a C compiler right now, so I can't confirm if it would or not would not work with signed integers. If memory serves me, the behavior of it might be undefined (though it might not matter, how I handle it).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With