0

Is there any limitation in bit shifting?

public static void main(String args[])
{
   int i=10;
   System.out.println(i<<32);
}

Output is 10

But I know its incorrect.

Answer should be 10*232 = 4.29*1010

Why is this?

Maroun
  • 94,125
  • 30
  • 188
  • 241
NipunR
  • 61
  • 2
  • 2
  • 7
  • 1
    A Java int is a 32bit, two-complement signed integer; I am surpised at all the the output of your prorgam is 10... – fge Feb 16 '14 at 13:26
  • @Nipun but then your answer wouldn't fit in an int... – Leo Feb 16 '14 at 13:34
  • You can check another question similar to it [http://stackoverflow.com/questions/14817639/java-bit-operations-shift](http://stackoverflow.com/questions/14817639/java-bit-operations-shift) – Devavrata Feb 16 '14 at 13:36
  • thanx I got the answer by using long i=10 yes int can't store that much size of value – NipunR Feb 16 '14 at 13:37
  • If read the spec, shifting is always modulo the bit length of the shiftee. (This is the way the hardware usually works anyway, so Java defined it that way to permit the simplest deterministic implementation.) – Hot Licks Feb 16 '14 at 13:47
  • Most important thing is: If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & with the mask value 0x1f. The shift distance actually used is therefore always in the range 0 to 31, inclusive. so i<<32 here 32 = 0010000 five lowest-order bits of the right-hand operand = 00000 i<<32 == i<<0 thankyou all to help me to understand this – NipunR Feb 16 '14 at 14:35

2 Answers2

3

Yes, the shift-factor is modulo'ed by:

  • 32, if the type of the shifted operand is char, short or int.
  • 64, if the type of the shifted operand is long.
barak manos
  • 29,648
  • 10
  • 62
  • 114
1

Since i is an int, only the 5 lowest bits are used.

The last 5 bits of 32 are 0:

Your program is equivalent to:

System.out.println(i<<0);

Which doesn't change the number.

If you want this to work, you should use long instead. See this link for good explanation.

Maroun
  • 94,125
  • 30
  • 188
  • 241