在小端与大端的类型转换

时间:2014-04-10 11:50:52

标签: c visual-c++ assembly disassembly

使用下面的代码,我已经研究了MS-VC ++中的反汇编

int main() {
int a = 0x7fffee
    ,as; //initialization in hex 
short b = 0x7fff
    ,bs;
//the format specifier %hp of %hd prints lower 2bytes only
printf("a(in dec) = %d : b(in dec) = %d \n",a,b);
printf("a(in hex) = %p : b(in hex) = %p \n",a,b); 

as = a << 2;
printf("(a << 2) = %p \n",as);
as = (int)b;
printf("(int)b = %p \n",as);

bs = (short)a; 
printf("(short)a = %hp \n",bs);
bs = (short)as;
printf("(short)as = %hp \n",bs);



return 0;
}

特别关注以下反汇编

17:       bs = (short)a; //bs gets only lower 2 bytes from a during typecast
0040B7F3   mov         dx,word ptr [ebp-4]
0040B7F7   mov         word ptr [ebp-10h],dx

对于从int转换为short的短路,使用dx寄存器。在输出中我看到

a(in dec) = 8388590 : b(in dec) = 32767
a(in hex) = 007FFFEE : b(in hex) = 00007FFF
(a << 2) = 01FFFFB8
(int)b = 00007FFF
(short)a = 0000FFEE //Interested to know what will be this value in Big Endian mode
(short)as = 00007FFF
Press any key to continue

我想知道

  1. 为什么(short)a = 0000FFEE以及为什么不(short)a = 007F or 7FFF

  2. Big Endian模式下引用的装配线的行为?任何人都可以解释一下,或者如何在MS-VC ++环境中将内存模型设置为大端或小端,以便我可以查看它!

1 个答案:

答案 0 :(得分:1)

  

为什么(短)a = 0000FFEE,为什么不(短)a = 007F或7FFF

©ISO / IEC ISO / IEC 9899:201x 编程语言 - C

  

6.3.1.3有符号和无符号整数

     

3 ...新类型已签名且值无法在其中表示;结果是实现定义的,或者引发实现定义的信号。

MSDN Demotion of Integers

  

当一个长整数被强制转换为short时,或者short被强制转换为char时,   保留最不重要的字节。


(short)a = 0000FFEE //Interested to know what will be this value in Big Endian mode

如上所述,它是实现定义的,但我们很难找到一个实现产生除最不重要字节之外的东西。