如何转换结构,在C字符数组 [英] How to convert struct to char array in C
问题描述
我想一个结构转换为字符数组通过网络发送。但是,我从字符数组一些奇怪的输出,当我这样做。
I'm trying to convert a struct to a char array to send over the network. However, I get some weird output from the char array when I do.
#include <stdio.h>
struct x
{
int x;
} __attribute__((packed));
int main()
{
struct x a;
a.x=127;
char *b = (char *)&a;
int i;
for (i=0; i<4; i++)
printf("%02x ", b[i]);
printf("\n");
for (i=0; i<4; i++)
printf("%d ", b[i]);
printf("\n");
return 0;
}
下面是输出a.x的各种值(在x86上使用gcc):结果
127:结果
7F 00 00 00结果
127 0 0 0结果
Here is the output for various values of a.x (on an X86 using gcc):
127:
7f 00 00 00
127 0 0 0
128:结果
ffffff80 00 00 00结果
-128 0 0 0结果
128:
ffffff80 00 00 00
-128 0 0 0
255:结果
FFFFFFFF 00 00 00结果
-1 0 0 0结果
255:
ffffffff 00 00 00
-1 0 0 0
256:结果
00 01 00 00结果
0 1 0 0结果
256:
00 01 00 00
0 1 0 0
我理解为127和256的值,但为什么数字将128当改变?为什么不只是为:
80 00 00 00
128 0 0 0
I understand the values for 127 and 256, but why do the numbers change when going to 128? Why wouldn't it just be: 80 00 00 00 128 0 0 0
我忘记做一些事情在转换过程中还是我忘了一些关于整数重新presentation?
Am I forgetting to do something in the conversion process or am I forgetting something about integer representation?
*注意:这只是一个小的测试程序。在实际的程序我有更多的结构,更好的变量名,我转化为little-endian的。结果
*编辑:格式
*Note: This is just a small test program. In a real program I have more in the struct, better variable names, and I convert to little-endian.
* formatting
推荐答案
的 X
本身的格式说明说,该参数是一个 INT
,并自号为负,的printf
需要8个字符显示 INT 所有四个非零字节code> -sized值。在
0
修饰符告诉填充用零输出,而 2
修饰符说,的最小输出应该是两个字符。据我所知,的printf
不提供一种方式来指定的最大的宽度,除了字符串。
The x
format specifier by itself says that the argument is an int
, and since the number is negative, printf
requires eight characters to show all four non-zero bytes of the int
-sized value. The 0
modifier tells to pad the output with zeros, and the 2
modifier says that the minimum output should be two characters long. As far as I can tell, printf
doesn't provide a way to specify a maximum width, except for strings.
现在那么,你只传递一个字符
,所以裸 X
告诉使用全功能 INT
即得到通过,而不是 - 因为默认参数推广 ...
参数。尝试 HH
修饰符告诉函数参数视为只是一个字符
而不是:
Now then, you're only passing a char
, so bare x
tells the function to use the full int
that got passed instead — due to default argument promotion for "...
" parameters. Try the hh
modifier to tell the function to treat the argument as just a char
instead:
printf("%02hhx", b[i]);
这篇关于如何转换结构,在C字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!