位操作-负数 [英] Bit manipulation- for negative numbers

查看:101
本文介绍了位操作-负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让整数 i = -5 的大小为2个字节.最左侧位的带符号位值是"1"(表示它是负数). 当我尝试执行右移操作时,我不应该期望第15位的"1"移至第14位吗?并给我一个高但积极的价值?

Let the size of integer i=-5 be 2 bytes. The signed bit value at the leftmost bit is '1'(which signifies that it is a negative number). When i am trying to do a right shift operation, should i not expect the '1' at the 15th bit position to shift to 14th position? and give me a high but positive value?

我尝试过的事情:

What i tried:

int i=5;
i>>1 // giving me 2 (i understand this)

int i=-5
i>>1 // giving me -3 (mind=blown)

推荐答案

负值的右移是实现定义的[expr.shift]/3

Right shifts of negative values are implementation-defined, [expr.shift]/3

E1 >> E2的值是E1右移E2位的位置. [..]. 如果E1具有带符号的类型和负值,则结果为 值是实现定义的.

The value of E1 >> E2 is E1 right-shifted E2 bit positions. [..]. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

大多数实现都使用所谓的 算术移位 保留并扩展符号位:

Most implementations use the so-called arithmetic shift though, which preserves and extends the sign-bit:

在二进制补码有符号二进制数上向右移 n 具有将其除以 2 n 的效果,但总是四舍五入 (朝向负无穷大).这与四舍五入的方式不同 通常以有符号整数除法(四舍五入)完成. 这种差异导致了多个编译器中的错误.

Shifting right by n bits on a two's complement signed binary number has the effect of dividing it by 2n, but it always rounds down (towards negative infinity). This is different from the way rounding is usually done in signed integer division (which rounds towards 0). This discrepancy has led to bugs in more than one compiler.

那么,当缩短到8位时,会发生以下情况.以2的补数表示-5是

So what happens is, when shortened down to 8 bit, the following. In two's complement -5 would be

1111 1011

算术右移后:

1111 1101

现在翻转并加一个以获得比较的正值:

Now flip and add one to get the positive value for comparison:

0000 0011 

对我来说看起来像三个.

Looks like a three to me.

这篇关于位操作-负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆