c - printf %i 在这种情况下如何工作?

标签 c arrays struct printf

<分区>

抱歉想问这个 question以另一种方式。

typedef   struct 
 { 
    char duo_word[8]; 
 } duo_word;


  duo_word duo_word_inst = { .duo_word = { 'º', '\b', '\x1', '\0', 'À', '\xe', '2', 'a' } };

  printf("          %i ", duo_word_inst); // gives 67770 but how?

以及如何将 67770 值提取到例如一个 int 变量?

最佳答案

printf%i 格式说明符需要一个int 作为它的参数。但是,您传递的是 duo_word。使用错误的 printf 格式说明符调用 undefined behavior .在这种情况下,您很“幸运”恰好打印了您想要的内容,但您不能依赖于这种行为。

假设结构中的前 4 个字节表示一个 little endian 格式的 32 位整数,您可以提取各个字节并将它们设置为整数,如下所示:

unsigned int value = 0;
value |= (unsigned char)duo_word_inst.duo_word[0];
value |= (unsigned char)duo_word_inst.duo_word[1] << 8;
value |= (unsigned char)duo_word_inst.duo_word[2] << 16;
value |= (unsigned char)duo_word_inst.duo_word[3] << 24;

关于c - printf %i 在这种情况下如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50822142/

相关文章:

c++ - C/C++如何复制结构?

c - 为什么存在系统调用

c - For循环超出限制继续执行(C语言)

shell - 使用 SIGTSTP 挂起子进程后,shell 没有响应

javascript - 比较两个对象数组并更新主数组中的元素 - JS

list - 戈朗 : create a slice of strutcs

c - 将 shellcode 声明为 char[] 数组和 char* 之间的区别?

javascript - 如何遍历收缩数组

在C中连接双指针char数组

c++ - 序列化二进制结构 gcc vs cl