Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain how this programs gives this output?

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.

like image 978
Nutty Noru Avatar asked Dec 03 '22 14:12

Nutty Noru


1 Answers

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
like image 169
Sam Varshavchik Avatar answered Jan 25 '23 23:01

Sam Varshavchik