问题描述
我右移-109由5位,和我预期-3,因为
-109 = -1101101(二进制)
由5位右移
-1101101 >> 5 = -11(二进制)= -3
I'm right-shifting -109 by 5 bits, and I expect -3, because-109 = -1101101 (binary)shift right by 5 bits-1101101 >>5 = -11 (binary) = -3
不过,我越来越-4代替。
有人能解释什么是错的?
But, I am getting -4 instead.Could someone explain what's wrong?
code我用:
int16_t a = -109;
int16_t b = a >> 5;
printf("%d %d\n", a,b);
我用GCC在Linux上,并在OSX哗,同样的结果。
I used GCC on linux, and clang on osx, same result.
推荐答案
这个事情是你不考虑负数
重新正确presentation。与右移位,移位(算术或逻辑的)的类型取决于被移位的值的类型。如果你投你的价值,一个无符号的价值,你可能会得到你期待什么:
The thing is you are not considering negative numbers representation correctly. With right shifting, the type of shift (arithmetic or logical) depends on the type of the value being shifted. If you cast your value to an unsigned value, you might get what you are expecting:
int16_t b = ((unsigned int)a) >> 5;
您在您例如使用 -109
(16位)。 109
中的位是:
You are using -109
(16 bits) in your example. 109
in bits is:
00000000 01101101
如果你拿的 109
2的补你:
If you take's 109
2's complement you get:
11111111 10010011
那么,你是5右移位数 11111111 10010011
:
__int16_t a = -109;
__int16_t b = a >> 5; // arithmetic shifting
__int16_t c = ((__uint16_t)a) >> 5; // logical shifting
printf("%d %d %d\n", a,b,c);
将产生:
-109 -4 2044
这篇关于右位移给错误的结果,可有人解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!