left shift magic
I have code:
signed short a = -32740;
float c;
float b;
b = (signed short)(a << 4);
c = a << 4;
printf("开发者_运维技巧(signed short)(a << 4): %f\n", b);
printf("(a << 4): %f\n", c);
output:
(signed short)(a << 4): 448.000000
(a << 4): -523840.000000
Why 16 senior registers not reset after the shift (c = a << 4;
)?
Program executed on x86 machine with 32-bit linux.
b = (signed short)(a << 4);
This line does the following:
- Calculate (a << 4). The calculation is done with integers (default in C). The result is: -523840
- Truncate the result (by dropping bits) to 16 bit by casting to signed short. (result is 448)
- convert the result to float (no change in value)
c = a << 4;
This line does the following:
- Calculate (a << 4). The calculation is done with integers (default in C). The result is: -523840
- convert the result to float (no change in value)
The fact that 'a' is declared as a signed short does not make a difference because all calculations are always done with the int datatype. I assume that your system has 32 bit integers.
精彩评论