假设负binary number表示在two's complement, how can we guarantee the sign is preserved?
假设我们用四位表示十进制数 -5
: 1011
,并且想要左移一个位置乘以2:
1011 << 1
此操作返回0110,即6, not -10 as we would have hoped .
(我假设这只是第二位为0的负数的情况,即负数接近某个范围的最小可表示负数)
假设负binary number表示在two's complement, how can we guarantee the sign is preserved?
假设我们用四位表示十进制数 -5
: 1011
,并且想要左移一个位置乘以2:
1011 << 1
此操作返回0110,即6, not -10 as we would have hoped .
(我假设这只是第二位为0的负数的情况,即负数接近某个范围的最小可表示负数)
1 回答
OP在这里 . 我找到了问题的答案 .
向左移动可能会触发arithmetic overflow .
two's complement系统可表示的数字范围是
-(2^(n-1))
到2^(n-1)-1
,其中n
是可用的位数, including the sign bit (MSB). 因此,在上面的示例中,每个数字使用4位,可能值的范围是-8
到7
,包括端值 .向左移动
m
位将乘以2^m
. 因此,在上面的示例中,-5 << 1
将产生-10
,这超出了4位有符号表示中可能数字的范围 - 这是溢出 .总之,在使用ASL乘以2的幂时,重要的是确保产品位于可能值的范围内 .