Java Bitwise AND and OR Exclusive OR and shift operators
If you have done some low level programming in C or other language, you must be familar with the bitwise operators. Java, too, provides bitwise operators. The table below explains the details of these bitwise operators Java Bitwise Operators
Operator | Meaning |
~ | Complement |
& | bitwise AND |
| | bitwise OR |
>> | bitwise shift right |
<< | Bitwise shift left |
The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the integral types ( If you apply it to byte type - they expand it to integer - see explanation here , making every "0" a "1" and every "1" a "0".
The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator ">>" 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. The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.
The bitwise & operator performs a bitwise AND operation.
The bitwise ^ operator performs a bitwise exclusive OR operation.
The bitwise | operator performs a bitwise inclusive OR operation.
Let us take examples. First we need to understand how an integer is represented in Java. An integer in Java is 4 bytes long and has value ranging from -2,147,483,648 to 2,147,483,647 and is represented as 2's complement.
|
If you compile and run this program, you will get the output as follows
C:\Program Files\Java\jdk1.7.0_17\bin>java bitwise 5's complement is 6 |
To understand why 5's complement is -6, you need to know about 2's complement. In binary term, 5 is represented as
00000000 00000000 00000000 00000101
Its complement will be
11111111 11111111 1111111 11111010
Which represents -6 in 2's complement.
The following code represents the rest of the bitwise operators
|
If you compile and run this program, you will get the output as follows
x & y is 3840 x | y is 65520 x >> y is 4080 x << y is 1044480 x ^ y is 1044480 x & y is 00000f00 x | y is 0000fff0 x >> y is 00000ff0 x << y is 000ff000 x ^ y is 0000f0f0 |