【发布时间】:2016-03-19 01:59:21
【问题描述】:
我一直试图在 C 中打印 unsigned short int 值,但没有成功。据我所知,这是一个 16 位的值,所以我尝试了几种不同的方法将这 2 个字节一起打印,但我只能在逐字节打印时正确打印。
请注意,我想以十进制和十六进制格式打印这 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。 -
是的,抱歉,我在复制粘贴,弄乱了数字。已编辑。
标签: c printf unsigned-integer