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 !
One can make judicious use of casting to do this easily. Just cast the char buffer to the type you want.
Your first method may result in better code, because in the second one the compiler must assume that the pointers
data
andvalue
can alias (though this may be mitigated if the compiler is able to inline the function where it is used).If you have a C99 compiler, you may want to take advantange of
uint32_t
,inline
and for the second variant,restrict
.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
.You can write:
This implementation ensures that the byte ordering is the correct independently from the underlying architecture.