Hi, when you push 1 to 31 times left it overwrite the sign bit thus turning it to a neg number(1 << 31) It will looks like 10000000...(put 31 zeroes) etc. To find out the real negative number take the two's complement which will give -2147483648. Now it is shifting to the right using the >> signed shift operator, 111111111.... Taking the 2's complement we will get it is -1. Now if it is shifted right it will continues to 1111111... making it -1. Thus the value of i is -1

In the second question the bit position is 00000000....1(put 31 zeroes), a single right shift itself push the 1 out and it becomes 0. Thus further right shift makes no change. so j becomes 0.

Hi there even I was struggling sometime with these bit juggling game till some kind souls explained me how it's done :- int i = 1; 2: i <<= 31; 3: i >>= 31; 4: i >>= 1;

line 2 results :- 10000000000000000000000000000000

line 3 results:- 11111111111111111111111111111111 [all gaps preceeding the '1' on line 2 results are prefixed with a '1']

line 4 results in: 11111111111111111111111111111111 [ drop the last '1' on line 3 result, and fill the empty space created LHS with a '1']

this # is -ve , see the '1' on the extreme LHS , which decides this fact. so flip all bytes:- 00000000000000000000000000000000 and add 1 resulting in 00000000000000000000000000000001 thus the final outcome is -ve 1 or -1.

also go for Arnab's theory of elimination, in this situation that seems to be the most smartest thing to do...

apart from giving the Exam and cracking it maybe in style,what 'real life value' this bit game has, confounds reasoning.

nachagoni rishi
Greenhorn

Joined: Oct 14, 2004
Posts: 26

posted

0

Thankyou vipin,Arnab NettyPoestel for the detailed explanation.

Don't get me started about those stupid light bulbs.