int x = -2139062144; //In binary: 10000000100000001000000010000000
int k = x << 1;
k
is 16843008
(binary: 1000000010000000100000000
), and I don't understand why?
How did 10000000100000001000000010000000
change into 1000000010000000100000000
by just one left bit shift?
I expected it to be: 10000001000000010000000100000000
conserving the sign as in right bit shift sign is conserved.
Very simple.
Your int
can carry only a maximum of 32 bits. Well, exactly 32 bits, all the time.
In
10000000100000001000000010000000
the most significant, leading bit, is 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
00000001000000010000000100000000
as a result, or:
1000000010000000100000000
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With