环境:VC6.0
typedef union
{
unsigned char pos[4];
unsigned int id;
}ID;
ID id;
文件第一行:0x01,0x02,0x03,0x04, "1st at " "a b"
问题:fscanf(fp, "%x,%x,%x,%x,", &id.pos[0], &id.pos[1], &id.pos[2], &id.pos[3]);
结果id.id = 0x04030201; 这可能是因为反了
于是:fscanf(fp, "%x,%x,%x,%x,", &id.pos[3], &id.pos[2], &id.pos[1], &id.pos[0]);
结果id.id = 0x00000004; 奇怪了
找原因: fscanf(fp, "%x,", &id.pos[3]); //执行完该语句,id.id = 0x01000000
fscanf(fp, "%x,", &id.pos[2]); //执行完该语句,id.id = 0x00020000
fscanf(fp, "%x,", &id.pos[1]); //执行完该语句,id.id = 0x00000300
fscanf(fp, "%x,", &id.pos[0]); //执行完该语句,id.id = 0x00000004
为什么呢?地址对齐?
fscanf(fp, "%x,", &id.pos[0]); //执行完该语句,id.id = 0x00000001
fscanf(fp, "%x,", &id.pos[1]); //执行完该语句,id.id = 0x00000201
fscanf(fp, "%x,", &id.pos[2]); //执行完该语句,id.id = 0x00030201
fscanf(fp, "%x,", &id.pos[3]); //执行完该语句,id.id = 0x04030201
虽然结果反了,但工作正常。
&id.pos[3]的地址>......>&id.pos[0]的地址
id.id = 0x55555555;
fscanf(fp, "%x,", &id.pos[3]); //执行完该语句,id.id = 0x01555555
fscanf(fp, "%x,", &id.pos[2]); //执行完该语句,id.id = 0x00025555
fscanf(fp, "%x,", &id.pos[1]); //执行完该语句,id.id = 0x00000355
fscanf(fp, "%x,", &id.pos[0]); //执行完该语句,id.id = 0x00000004
我想原因找到了:
memory address: 00 01 02 03 04 05 06
pos[0] pos[1] pos[2] pos[3] n n n
给pos[3]赋0x01 01 00 00 00
给pos[2]赋0x02 02 00 00 00
给pos[1]赋0x03 03 00 00 00
给pos[0]赋0x04 04 00 00 00
所以最终结果总是04。上述结果是我的推论。
修改输入0x01010101,0x02020202,0x03030303,0x04040404, "1st at " "a b"
进行调试,打开内存视图进行观察,推论是正确的。
结论就是%x返回的可能是4字节int,或其它。如何处理将%x返回成一个字节的呢?