Bitwise Operators can be applied to the Integer types: long , int , short , char , byte
| Operator | Operation |
|---|---|
| ~ | Bitwise unary NOT |
| & | Bitwise AND |
| ^ | Bitwise exclusive OR |
| >> | Shift Right |
| >>> | Shift Right zero fill |
| << | Shift left |
| &= | Bitwise AND assignment |
| = | |
| ^= | Bitwise exclusive OR assignment |
| >> = | Shift right assignment |
| >>> = | Shift right zero fill assignment |
| << = | shift left assignment |
(Signed) Left shift ( << )
(Signed) Right shift ( >> )
Unsigned Right Shift ( >>> )
- Convert number to binary ( if not binary ).
- Move the numbers to the left and replace least significant bits with zero.
- Eg: 20 << 4 (320)
1. Assume 8 bit system ( 20 ⇒ 0b00010100 )
2. shifting four positions to left and fill least significant bits with 0. i.e; simply add four zeroes at the end
0b000101000000 ⇒ 0b101000000
3. 0b101000000 = 320Ex: 20 << 4 = 20 * ( 2 ^ 4 ) = 20 * 16 = 320
- convert number to binary.
- Move the numbers to the right and replace most significant bits with signed value.
- Ex: 20 >> 4 (1)
1. Assume 8 bit system ( 20 ⇒ 0b00010100 )
2. shifting four positions to right and replace most significant bits
with 0 (signed bit)
i.e; simply remove last 4 bits and add 4 sign bits 0 at the beginning
0b00010100 => 0b00000001 => 1- Ex: -20 >> 4 ( -2 )
1. Assume 8 bit system ( 20 ⇒ 0b00010100 ) ( -20 ⇒ 0b11101100 ) using 2’s compliment method
2. shifting four positions to right and replace most significant bits with 1(signed bit)
i.e; simply add 4 sign bits 1 at the beginning and remove last 4 bits
0b11111110 ⇒ using 2’s compliment ⇒ 0b00000010 ⇒ - 2Ex:
20 >> 4 ⇒ floor(20 / 2 ^4 ) ⇒ 20/16 ⇒ floor(1.xxx) ⇒ 1
-20 >> 4 ⇒ floor(-20 / 2 ^4 ) ⇒ -20/16 ⇒ floor(-1.xxx) ⇒ -2
- convert number to binary.
- Move the numbers to the right and replace most significant bits with 0.
- Ex: 20 >>> 4 (1) ( same as signed right shift for positive number )
1. Assume 8 bit system ( 20 ⇒ 0b00010100 )
2. shifting four positions to right and replace most significant bits with 0
i.e; simply remove last 4 bits and add 4 zeros at the beginning
0b00010100 => 0b00000001
3. 0b00000001 ⇒ 1- Ex: -20 >>> 4 (268435454)
1. Assume 8 bit system ( 20 ⇒ 0b00010100 ) ( -20 ⇒ 0b11101100 ) using 2’s
compliment method
2. shifting four positions to right and replace most significant bits with 0
i.e; simply add 4 zeros at the beginning and remove last 4 bits
0b00001110 ⇒ 14
-20 => 0b11111111111111111111111111101100 ( 32 bit system )
0b11111111111111111111111111101100 >>> 4
0b00001111111111111111111111111110 => 268435454 ( Decimal )