对于一个正整数,移位都比较清楚,但对一个负数移位的结果如何呢?
直接做测试,代码如下:
unsigned short value_test;
int result_test;
value_test = 0xe100; // -(31 << 8)
result_test = ((short)value_test >> 8);
printf("-(31 << 8) >> 8[%d] ", result_test);
value_test = 0xe100; // -(31 << 8)
result_test = ((short)value_test << 2);
printf("-(31 << 8) << 2[%d] ", result_test);
value_test = 0x1f00; // (31 << 8)
result_test = ((short)value_test >> 8);
printf(" (31 << 8) >> 8[%d] ", result_test);
value_test = 0x1f00; // (31 << 8)
result_test = ((short)value_test << 2);
printf(" (31 << 8) << 2[%d] .\r\n", result_test);
value_test = 0xf200; // -(14 << 8)
result_test = ((short)value_test >> 8);
printf("-(14 << 8) >> 8[%d] ", result_test);
value_test = 0xf200; // -(14 << 8)
result_test = ((short)value_test << 2);
printf("-(14 << 8) << 2[%d] ", result_test);
value_test = 0xe00; // (14 << 8)
result_test = ((short)value_test >> 8);
printf(" (14 << 8) >> 8[%d]", result_test);
value_test = 0xe00; // (14 << 8)
result_test = ((short)value_test << 2);
printf(" (14 << 8) << 2[%d] .\r\n", result_test);
输出结果为:
-(31 << 8) >> 8[-31] -(31 << 8) << 2[-31744] (31 << 8) >> 8[31] (31 << 8) << 2[31744] .
-(14 << 8) >> 8[-14] -(14 << 8) << 2[-14336] (14 << 8) >> 8[14] (14 << 8) << 2[14336] .
得出的结果为: 对负数,
1. 不化是左移,还是右移, 其符号位不变,
2. 对于负数移位,除开符号位外,移位的结果和其绝对值移位的值相等.