开发者

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:

  1. Calculate (a << 4). The calculation is done with integers (default in C). The result is: -523840
  2. Truncate the result (by dropping bits) to 16 bit by casting to signed short. (result is 448)
  3. convert the result to float (no change in value)

c = a << 4;

This line does the following:

  1. Calculate (a << 4). The calculation is done with integers (default in C). The result is: -523840
  2. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜