如何转换一个4字节的“字符串"?到uint32_t? [英] How to convert a 4-byte "string" to an uint32_t?
问题描述
基本上,我有一个字节串的数据,例如:\x00\x00\x00\x00 \x08\x00\x00\x00 \x05\x00\x00\x00
(空格仅用于可见性,实际字节串中没有空格字节).数据是小端的.
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.
现在,我需要提取第二个4字节组(\x08\x00\x00\x00
,它是128
)并将其设置为无符号长.因此,uint32_t
类型.
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.
基本上,我正在做的是:moveBlock(&gdata->str[4], &second_group, 4);
Basically, what I'm doing is: moveBlock(&gdata->str[4], &second_group, 4);
moveBlock
是宏的位置:#define moveBlock(src,dest,size) memmove(dest,src,size)
.
我使用该宏是因为如果有人想知道的话,我个人更喜欢参数的顺序.
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
是指向gchar *
(的指针ref.)
而gdata是GString *
(参考.).
second_group
被定义为uint32_t
.
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!
谢谢!
P.S:代码有点冗长和怪异,我认为遍历所有代码都不重要.除非有人要求,否则我不会不必要地使问题混乱
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
推荐答案
这是干净的便携式版本:
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];
这篇关于如何转换一个4字节的“字符串"?到uint32_t?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!