Search code examples
cbinary-dataglib

How to convert a 4-byte "string" to an uint32_t?


Basically, I have a byte-string of data like: \x00\x00\x00\x00 \x08\x00\x00\x00 \x05\x00\x00\x00 (spaces are used only for visibility, there are no space bytes in the actual byte-string). The data is little-endian.

Now, I need to extract the second 4-byte group (\x08\x00\x00\x00, which is 128) and turn them it an unsigned long. So, uint32_t type.

Basically, what I'm doing is: moveBlock(&gdata->str[4], &second_group, 4);

Where moveBlock is a macro: #define moveBlock(src,dest,size) memmove(dest,src,size). I use the macro because I personally prefer that order of parameters, if someone's wondering.

gdata->str is a pointer to a gchar *(ref. here) and gdata is a GString *(ref. here). second_group is defined as an uint32_t.

So, this works sometimes, but not always. I honestly don't know what I'm doing wrong!

Thanks!


P.S: The code it a bit lengthy and weird, and I don't think that going through it all would be relevant. Unless someone asks for it, I won't unnecessarily clutter the question


Solution

  • Here's the clean portable version:

    unsigned char *p = (void *)data_source;
    uint32_t x = p[0] + 256U*p[1] + 65536U*p[2] + 16777216U*p[3];