c - 打印 uint16_t 类型

标签 c printf uint16

我正在以这种方式读取二进制模式的文件:

fread(&pcap_header      ,sizeof(pcap_hdr_t      ),  1 , pFile);
fread(&pcaprec_header   ,sizeof(pcaprec_hdr_t   ),  1 , pFile);
fread(&ether_header     ,sizeof(ethernet_hdr_t  ),  1 , pFile);
fread(&ip_header        ,sizeof(ip_hdr_t        ),  1 , pFile);
fread(&tcp_header       ,sizeof(tcp_header_t    ),  1 , pFile);
fread(&modbus_header    ,sizeof(modbus_header_t ),  1 , pFile);

而上面的所有变量都被定义为它旁边的'sizeof()'函数中的类型。 我正在尝试提取文件的特定部分并进行打印。这部分的大小是 16 位,定义如下:

uint16_t     ip_len;

在“ip_hdr_t”类型中。我查看了 WireShark,看到了这 16 位的实际值,它是 0x0034。

我尝试了两件事:

  1. printf("size of ip header: %hu\n", ip_header.ip_len); 打印出 13312(好像位的值是 0x3400)
  2. 将结构划分为两个 8 位变量: uint8_t ip_len; uint8_t ip_len2; 并单独打印: printf("ip header 的大小: %hu\n", ip_header.ip_len); printf("ip header 的大小: %hu\n", ip_header.ip_len2);

这次我收到了输出:ip header 的大小:0 (0x00) IP header 的大小:52 (0x34) 这是正确答案。

我的问题是:第一次打印出了什么问题?

谢谢

最佳答案

你有一个 endianness问题;您的平台与您使用的协议(protocol)不具有相同的字节顺序。您需要交换字节的顺序。

如果您使用的是 POSIX 兼容系统,则可以使用 ntoh family of functions .

我不确定是否有类似的东西,例如 window 。

关于c - 打印 uint16_t 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15501238/

相关文章:

C 使用 openssl 执行 HTTPS 请求

c - 如何使用正确的参数在 C 中调用 execl()?

c - 发现段错误,但正在优化之前的消息

c - 为什么我在执行 printf ("%f",3/2) 时得到 2.168831?

C - Arduino - 无法将 'uint8_t*' 转换为 'uint16_t*'

c - 提取无符号 32 位整数的上下字

C UINT16 如何正确?

c - Internet Checksum 函数是否移动 8bits

c - 由于某种原因最后一个字母是输入+1

c - 文本文件 fscanf 问题