0

Using the below code, i have looked into the disassembly in 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;
}

Specially interested in following disassembly

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

For typecasting into short from int, dx register is used. In output i see

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

I want to know

  1. Why (short)a = 0000FFEE and why not (short)a = 007F or 7FFF

  2. The behaviour of the quoted assembly line in Big Endian mode? Can anyone explain me, or how can I set memory model in MS-VC++ environment to either big or little endian, so that I can check this out!

unwind
  • 391,730
  • 64
  • 469
  • 606
nmxprime
  • 1,506
  • 3
  • 25
  • 52

1 Answers1

1

Why (short)a = 0000FFEE and why not (short)a = 007F or 7FFF

©ISO/IEC ISO/IEC 9899:201x Programming languages — C

6.3.1.3 Signed and unsigned integers

3 ... the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

MSDN Demotion of Integers

When a long integer is cast to a short, or a short is cast to a char, the least-significant bytes are retained.


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

As stated above, it is implementation-defined, but we would have a hard time finding an implementation which yields something other than the least-significant bytes.

Armali
  • 18,255
  • 14
  • 57
  • 171