有人可以解释这个程序如何提供这个输出?

时间:2020-12-15 01:33:53
int x = -2139062144;  //In binary: 10000000100000001000000010000000
int k = x << 1;

k is 16843008 (binary: 1000000010000000100000000), and I don't understand why?

k是16843008(二进制:1000000010000000100000000),我不明白为什么?

How did 10000000100000001000000010000000 change into 1000000010000000100000000 by just one left bit shift?

10000000100000001000000010000000如何通过一个左移位变为1000000010000000100000000?

I expected it to be: 10000001000000010000000100000000 conserving the sign as in right bit shift sign is conserved.

我期望它是:10000001000000010000000100000000保存符号,因为右移位符号是守恒的。

2 个解决方案

#1


10  

Very simple.

Your int can carry only a maximum of 32 bits. Well, exactly 32 bits, all the time.

你的int最多只能携带32位。那么,一直是32位。

In

 10000000100000001000000010000000

the most significant, leading bit, is 1.

最重要的领先位是1。

What do you think happens to this doomed bit, as a result of a left shift?

由于左移,您认为这个注定的位会发生什么?

It's gone. It ceased to exist. It joined the choir invisible. It's an ex-bit.

它消失了。它不复存在。它加入了合唱团隐形。这是一个前位。

And, of course, there is a freshly-born, 0 bit in the least significant position. So you end up with

当然,在最不重要的位置有一个刚出生的0位。所以你最终得到了

00000001000000010000000100000000

as a result, or:

结果,或:

1000000010000000100000000

#2


7  

Left shift of a negative value has undefined behaviour. Anything may happen, including what you see.

负值的左移具有未定义的行为。任何事情都可能发生,包括你所看到的。

http://en.cppreference.com/w/cpp/language/operator_arithmetic#Bitwise_shift_operators

#1


10  

Very simple.

Your int can carry only a maximum of 32 bits. Well, exactly 32 bits, all the time.

你的int最多只能携带32位。那么,一直是32位。

In

 10000000100000001000000010000000

the most significant, leading bit, is 1.

最重要的领先位是1。

What do you think happens to this doomed bit, as a result of a left shift?

由于左移,您认为这个注定的位会发生什么?

It's gone. It ceased to exist. It joined the choir invisible. It's an ex-bit.

它消失了。它不复存在。它加入了合唱团隐形。这是一个前位。

And, of course, there is a freshly-born, 0 bit in the least significant position. So you end up with

当然,在最不重要的位置有一个刚出生的0位。所以你最终得到了

00000001000000010000000100000000

as a result, or:

结果,或:

1000000010000000100000000

#2


7  

Left shift of a negative value has undefined behaviour. Anything may happen, including what you see.

负值的左移具有未定义的行为。任何事情都可能发生,包括你所看到的。

http://en.cppreference.com/w/cpp/language/operator_arithmetic#Bitwise_shift_operators