Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login

# Bitwise

hanmeng
Greenhorn

Joined: Aug 16, 2000
Posts: 26
The following code will print
1: int i = 1;
2: i <<= 31;<br /> 3: i >>= 31;
4: i >>= 1;
5:
6: int j = 1;
7: j <<= 31;<br /> 8: j >>= 31;
9:
10: System.out.println("i = " +i );
11: System.out.println("j = " +j);
A) i = 1
j = 1
B) i = -1
j = 1

C) i = 1
j = -1

D) i = -1
j = -1
Doit
Ranch Hand

Joined: Aug 03, 2000
Posts: 169
-1
-1
hema janani
Ranch Hand

Joined: May 19, 2000
Posts: 70
To Hanmeng
Question:
i=1
i<<31<br /> i>>31
i>>1
ans:
in binary 1 is represented as:
0000 0000 0000 0000 0000 0000 0000 0001
now 1<<=31 that means :make a left shift by 31<br /> therefore when you drop left 31 bits & filling new bits by 0 (becoz it is left shift )gives you<br /> 1000 0000 0000 0000 0000 0000 0000 0000<br /> now i>>31
making right shift by 31 gives you(becoz it's a right shift fill new bits by most significant bit ie.in our case 1)
1111 1111 1111 1111 1111 1111 1111 1111
now the last step i>>1
1111 1111 1111 1111 1111 1111 1111 1111
which gives i=-1

same with j,j=1
0000 0000 0000 0000 0000 0000 0000 0001
j<<31
1000 0000 0000 0000 0000 0000 0000 0000
j <<31
1111 1111 1111 1111 1111 1111 1111 1111
that gives j=-1
shifting by left shift 31 means same as remaining with 1(32-31=1)for an int.
I hope it helps
Hema

subject: Bitwise