[英]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). 基本上,我有一个字节字符串数据,例如:
\\x00\\x00\\x00\\x00 \\x08\\x00\\x00\\x00 \\x05\\x00\\x00\\x00
(空格仅用于可见性,其中没有空格字节实际的字节字符串)。 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. 现在,我需要提取第二个4字节组(
\\x08\\x00\\x00\\x00
,即128
)并将其设置为无符号长。 So, uint32_t
type. 因此,
uint32_t
类型。
Basically, what I'm doing is: moveBlock(&gdata->str[4], &second_group, 4);
基本上,我正在做的是:
moveBlock(&gdata->str[4], &second_group, 4);
Where moveBlock
is a macro: #define moveBlock(src,dest,size) memmove(dest,src,size)
. 其中
moveBlock
是宏: #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 ). gdata->str
是指向gchar *
( 此处引用 )的指针,而gdata是GString *
( 此处引用 )。 second_group
is defined as an uint32_t
. second_group
定义为uint32_t
。
So, this works sometimes , but not always. 因此,这有时有效 ,但并非总是如此。 I honestly don't know what I'm doing wrong!
老实说,我不知道我在做什么错!
Thanks! 谢谢!
PS: The code it a bit lengthy and weird, and I don't think that going through it all would be relevant. PS:代码有点冗长和怪异,我认为遍历所有代码都不重要。 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];
the "string" is actually in big endian. “字符串”实际上是大尾数形式。
then you need be32toh
or write it yourself like this: 那么您需要
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;
}
Note: I did not tried the code, there might be errors, but you get the idea 注意:我没有尝试过代码,可能有错误,但是您知道了
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.