如何将 4 字节“字符串”转换为到 uint32_t?
基本上,我有一个字节字符串数据,例如: \x00\x00\x00\x00 \x08\x00\x00\x00 \x05\x00\x00\x00
(空格仅用于可见性,实际字节串中没有空格字节)。数据是小尾数。
现在,我需要提取第二个 4 字节组(\x08\x00\x00\x00
,即 128
)并将其转换为无符号长整型。因此,uint32_t 类型。
基本上,我正在做的是: moveBlock(&gdata->str[4], &second_group, 4);
其中 moveBlock
是一个宏: <代码>#define moveBlock(src,dest,size) memmove(dest,src,size)。 我使用宏是因为我个人更喜欢参数的顺序(如果有人想知道的话)。
gdata->str
是指向 gchar *
(参考此处) gdata 是一个 GString *
(参考。此处)。 second_group
定义为 uint32_t
。
所以,这有时有效,但并非总是有效。老实说,我不知道我做错了什么!
谢谢!
PS:代码有点冗长和奇怪,我认为遍历所有代码没有意义。除非有人要求,否则我不会不必要地混淆问题
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是干净的便携式版本:
Here's the clean portable version:
您可以尝试
strtoul()
编辑:必须以 null 终止数组才能使其成为字符串。
You could try
strtoul()
Edit: you will have to null terminate your array to make it a string.
“字符串”实际上是大端字节序。
那么你需要
be32toh
或自己这样写:注意:我没有尝试代码,可能会有错误,但你明白了
the "string" is actually in big endian.
then you need
be32toh
or write it yourself like this:Note: I did not tried the code, there might be errors, but you get the idea