Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deserialize function ( byte array to uint32 )

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 !

like image 952
emge Avatar asked May 26 '11 21:05

emge


1 Answers

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.

like image 142
Roland Illig Avatar answered Sep 24 '22 09:09

Roland Illig