Whats the best way to write a deserialize function to convert a byte array into a 32 bit unsigned integer?
typedef unsigned long uint32;
uint32 deserialize_uint32(unsigned char *buffer)
{
uint32 value = 0;
value |= buffer[0] << 24;
value |= buffer[1] << 16;
value |= buffer[2] << 8;
value |= buffer[3];
return value;
}
unsigned char* deserialize_uint32B(unsigned char *buffer, uint32* value)
{
*value = 0;
*value |= buffer[0] << 24;
*value |= buffer[1] << 16;
*value |= buffer[2] << 8;
*value |= buffer[3];
return buffer + 4;
}
thanks! or if there's even a better way please let me know.. thanks !
I prefer your first variant over the second. Or you might exploit parallel processing by having four local variables that take the individual bytes shifted by the correct amount. Then, in the final line you return b0shifted | b1shifted | b2shifted | b3shifted
.
Anyway, it all depends on your compiler. Your second variant contains more load/store operations, so the first variant has fewer abstract operations.
Concerning readability, understandability and clarity, your first variant is great. It also works on whatever weird platform you are using (endianess, alignment), provided that CHAR_BIT == 8
.
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