如何在C中将struct转换为char数组 [英] How to convert struct to char array in C

查看:15
本文介绍了如何在C中将struct转换为char数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 struct 转换为 char 数组以通过网络发送.但是,当我这样做时,我会从 char 数组中得到一些奇怪的输出.

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("
");
   for (i=0; i<4; i++)
      printf("%d ", b[i]);
   printf("
");
   return 0;
}

这是 a.x 的各种值的输出(在使用 gcc 的 X86 上):
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 00128 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

我是在转换过程中忘记做某事,还是忘记了有关整数表示的事情?

Am I forgetting to do something in the conversion process or am I forgetting something about integer representation?

*注意:这只是一个小测试程序.在一个真正的程序中,我有更多的结构,更好的变量名,并且我转换为小端.
*格式化

*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 需要八个字符来显示 int 大小的值的所有四个非零字节.0 修饰符告诉用零填充输出,而 2 修饰符说 minimum 输出应该是两个字符长.据我所知,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.

那么现在,你只传递了一个 char,所以裸 x 告诉函数使用完整的 int 来代替— 由于..."参数的默认参数提升.尝试使用 hh 修饰符来告诉函数将参数仅视为 char:

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中将struct转换为char数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆