我一直在尝试使用C语言打印无符号短整型(unsigned short int)数值,但没有成功。据我所知,这是一个16位的值,因此我尝试了几种不同的方法来同时打印这2个字节,但只有在逐字节进行时才能正确打印。
请注意,我想以十进制和十六进制格式打印这16位,例如
我有这个结构体:
请注意,我想以十进制和十六进制格式打印这16位,例如
00 01
表示1
,另一个例子是:00 ff
表示255
。我有这个结构体:
struct arphdr {
unsigned short int ar_hrd;
unsigned short int ar_pro;
unsigned char ar_hln;
unsigned char ar_pln;
unsigned short int ar_op;
// I'm commenting the following part because I won't need it now
// for the explanation
/* unsigned char __ar_sha[ETH_ALEN];
unsigned char __ar_sip[4];
unsigned char __ar_tha[ETH_ALEN];
unsigned char __ar_tip[4]; */
};
这个函数:
void print_ARP_msg(struct arphdr arp_hdr) {
// I need to print the arp_hdr.ar_hrd in both decimal and hex.
printf("Format HW: %04x\n", arp_hdr.ar_hrd);
printf("Format Proto: %04x\n", arp_hdr.ar_pro);
printf("HW Len: %x\n", arp_hdr.ar_hln);
printf("Proto Len: %x\n", arp_hdr.ar_pln);
printf("Command: %04x\n", arp_hdr.ar_op);
}
print_ARP_msg函数返回以下内容:
硬件类型格式: 0100
协议类型格式: 0008
硬件地址长度: 6
协议地址长度: 4
命令: 0100
结构体的十六进制值为"00 01 08 00 06 04 00 01",所以我不知道为什么arp_hdr.ar_hrd字段的值是0100。
此外,我编写了一个将结构体以十六进制形式打印的函数,以确保我做得正确。我已经验证了所有字段都被正确赋值。
PS:在提问之前,我意识到它输出了正确的十六进制值但是颠倒了顺序。这可能与小/大端差异有关吗?
0x00ff
不是16
。 - EOF