如何将 4 字节“字符串”转换为到 uint32_t?

发布于 2025-01-07 03:15:10 字数 917 浏览 3 评论 0原文

基本上,我有一个字节字符串数据,例如: \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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

屋檐 2025-01-14 03:15:10

这是干净的便携式版本:

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

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];
凡间太子 2025-01-14 03:15:10

您可以尝试 strtoul()

编辑:必须以 null 终止数组才能使其成为字符串。

You could try strtoul()

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

森林迷了鹿 2025-01-14 03:15:10

“字符串”实际上是大端字节序。

那么你需要 be32toh 或自己这样写:

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

注意:我没有尝试代码,可能会有错误,但你明白了

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文