Ben Chuanlong Du's Blog

It is never too late to learn.

Bitwise Operators in Java

Java Operator Precedence

  1. The Bitwise operators has relative low precedence. They have lower precedence than arithmatical operators. It is suggested that you use parentheses when you mix lower precendenc (bitwise opertors, ternary opertor, etc.) and high precendenc operators together.

  2. There is no unsigned left shift operator in Java. https://www.quora.com/Why-is-there-no-unsigned-left-shift-operator-in-Java

In [7]:
System.out.println(1 << 5)
32
Out[7]:
null
In [6]:
System.out.println(1 << 5 - 1)
16
Out[6]:
null
In [13]:
System.out.println(1 << 30)
1073741824
Out[13]:
null
In [7]:
System.out.println(1 << 31)
-2147483648
Out[7]:
null
In [14]:
System.out.println(Integer.toBinaryString(1 << 31))
10000000000000000000000000000000
Out[14]:
null

The shift oprator is cyclical.

In [15]:
System.out.println(Integer.toBinaryString(1 << 32))
1
Out[15]:
null

Unsigned Right Shift Operator (>>>)

In [8]:
System.out.println(1 >>> 31);
0
Out[8]:
null
In [3]:
System.out.println(Integer.toBinaryString(-4))
11111111111111111111111111111100
Out[3]:
null
In [1]:
System.out.println(-4 >>> 28);
15
Out[1]:
null
In [5]:
System.out.println(Integer.toBinaryString(-1))
11111111111111111111111111111111
Out[5]:
null
In [4]:
System.out.println(-4 >> 28)
-1
Out[4]:
null
In [12]:
System.out.println(1 <<< 3);
illegal start of type
 System.out.println(1 <<< 3)
                          ^  

illegal start of expression
 System.out.println(1 <<< 3)
                           ^^ 

')' expected
 System.out.println(1 <<< 3)
                            ^

';' expected

^

reached end of file while parsing
 }
  ^
In [3]:
System.out.println(1 << 32)
1
Out[3]:
null
In [4]:
System.out.println(1 << 33)
2
Out[4]:
null
In [6]:
System.out.println(~0)
-1
Out[6]:
null
In [5]:
System.out.println(Integer.toBinaryString(-1))
11111111111111111111111111111111
Out[5]:
null

Comments