Deserialization function (byte array - uint32)

What is the best way to write a deserialization function to convert a byte array to 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;
    }

thank! or if there is even a better way, please let me know .. thanks!

+3
source share
4 answers

I prefer your first option in a second. Or you can use parallel processing, having four local variables that accept separate bytes shifted by the correct amount. Then in the final line you return b0shifted | b1shifted | b2shifted | b3shifted.

In any case, it all depends on your compiler. The second option contains more load / storage operations, so the first option has fewer abstract operations.

, , . , (endianess, alignment), , CHAR_BIT == 8.

+2

:

#include <arpa/inet.h>

uint32_t deserialize_uint32(unsigned char *buffer) {
    uint32_t res = *((uint32_t *) buffer);
    return ntohl(res);
}

unsigned char *serialize_uint32(unsigned char *buffer, uint32_t *value) {
    *((uint32_t *) buffer) = htonl(*value);
    return buffer;
}

, .

0

, , data value ( , , ).

C99, uint32_t, inline restrict.

0

You can make smart use of casting to make it easy. Just add a char buffer to the type you want.

uint32 deserialize_uint32(unsigned char *buf)
{
    uint32 *x = (uint32*)buf;
    return *x;
}

unsigned char * deserialize_uint32B(unsigned char *buffer, uint32* value)
{
    *(uint32*)buffer = *value;
    return buffer;
}
0
source

All Articles