How to convert a 4-byte “string” to an uint32_t?

2019-06-06 08:30发布

问题:

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

回答1:

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];


回答2:

You could try strtoul()

Edit: you will have to null terminate your array to make it a string.



回答3:

the "string" is actually in big endian.

then you need be32toh or write it yourself like this:

uint32_t conver(const void *src){
   const char *s = src;
   const char out[] = { s[3],s[2],s[1], s[0] };
   return (uint32_t) out;
}

Note: I did not tried the code, there might be errors, but you get the idea