Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is 1>>32 == 1?

I'm wondering if perhaps this is a JVM bug?

java version "1.6.0_0" OpenJDK Runtime Environment (IcedTea6 1.4.1) (6b14-1.4.1-0ubuntu13) OpenJDK 64-Bit Server VM (build 14.0-b08, mixed mode)

class Tmp {     public static void main(String[] args) {         System.out.println("1>>1 = "+(1>>1));         System.out.println("1>>2 = "+(1>>2));         System.out.println("1>>31 = "+(1>>31));         System.out.println("1>>32 = "+(1>>32));         System.out.println("1>>33 = "+(1>>33));     } } 

produces this when I run it:

1>>1 = 0 1>>2 = 0 1>>31 = 0 1>>32 = 1 <---------- should be 0 i think 1>>33 = 0 

I also get the same results for any multiple of 32.

do I need to write my own right-shift to check for this?

like image 463
Arthur Ulfeldt Avatar asked Jul 03 '10 05:07

Arthur Ulfeldt


People also ask

What does >> mean code?

>> is the signed right shift operator. It shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. When you shift right two bits, you drop the two least significant bits.

What does >> in Java mean?

Object Oriented Programming Fundamentals The >> operator is a signed right shift operator and >>> is an unsigned right shift operator. The left operands value is moved right by the number of bits specified by the right operand.

What is >> in bit manipulation?

The Operators >> is the arithmetic (or signed) right shift operator. >>> is the logical (or unsigned) right shift operator. << is the left shift operator, and meets the needs of both logical and arithmetic shifts.

What is this << operator called?

This operator (<<) applied to an output stream is known as insertion operator.


1 Answers

http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.22.1

15.19 Shift Operators

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 & (§15.22.1) with the mask value 0x1f. The shift distance actually used is therefore always in the range 0 to 31, inclusive.

If the promoted type of the left-hand operand is long, then only the six 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 & (§15.22.1) with the mask value 0x3f. The shift distance actually used is therefore always in the range 0 to 63, inclusive.

(emphasis mine)

like image 106
rwong Avatar answered Oct 14 '22 09:10

rwong