The bitwise operators provided by Java are: Left (<<), right Shift (>>), unsigned Right shift (>>>), Bit and (&), bit or (|), bit non (~), bitwise XOR (^), except for bits (~), which are unary operators. All the others are two-dollar operators.
Print Binary:
System.out.printIn (integer.tobinarystring (2)); // result is ten.
1. Shift Left (<<)
Test1, move 5 to the left 2 bits:
Package Com.xcy; Public class Test { publicstaticvoid main (string[] args) { System.out.println ( 5<<2); // The result of the operation is }}
The result is 20, but how does the program work?
First, the 5 is converted to a 2-binary representation (in Java, integers are by default the int type, or 32-bit):
0000 0000 0000 0000 0000 0000 0000 0101 Then shift left 2 bit, low 0:
0000 0000 0000 0000 0000 0000 0001 10 binary to 20
2, right Shift (>>) , right shift the same, but the direction is not the same (feel and not say the same)
System.out.println (5>>2); // operation result is 1
or first turn 5 into a 2 binary representation:
0000 0000 0000 0000 0000 0000 0000 0101 Then right-shift 2-bit, high-fill 0:
xx00 0000 0000 0000 0000 0000 0000 0001
3, unsigned Right shift (>>>)
We know that in Java, the int type occupies 32 bits, can represent a positive number, or it can represent a negative number. A positive number is converted to binary with a maximum of 0, and the binary of negative numbers is up to 1
For example, 5 is converted into binary after:
1111 1111 1111 1111 1111 1111 1111 1011 (at the beginning of contact with the binary, I do not know that the highest bit is used to denote the positive and negative points, it was not always possible to understand. What you get is a positive number-_-).
We move the 5 right 3 bits, 5 to the right 3 bits and the unsigned right shift 3 bits respectively:
Package Com.xcy; Public class Test { publicstaticvoid main (string[] args) { System.out.println ( 5>>3); // The result is 0 . System.out.println ( -5>>3); // The result is -1 . System.out.println ( -5>>>3); // The result is 536870911 . }}
reference:http://blog.csdn.net/xiaochunyong/article/details/7748713
Java bit manipulation