DEV Community

Abhinav Pandey
Abhinav Pandey

Posted on • Updated on

Bitwise operations in Java

Bitwise complement

Using the symbol ~ you can get the bitwise complement of an integer.
It will reverse each bit of the binary representation including the sign.

int a = 2; // binary 0,00..10 (4 byte signed binary representation)
int b = ~a; // returns -3 -> binary 1,11...01 (sign changed and each bit reversed)
Enter fullscreen mode Exit fullscreen mode

Bitwise AND, OR, XOR

int a = 3; //     011 
int b = 5; //     101
int c = a & b; // 001 -> 1 if both bits are 1
int d = a | b; // 111 -> 1 if either it is 1
int e = a ^ b; // 110 -> 1 if both bits are different
Enter fullscreen mode Exit fullscreen mode

Shifting bytes

  1. Signed left shift - "<<" - shift each bit to the left. Add 0s to the empty space on the right.
  2. Signed right shift - ">>" - shift each bit to the right. Add 0s/1s (depending on sign, 0 for positive and 1 for negative numbers) to the empty space on the left.
  3. Unsigned right shift - ">>>" - shift each bit to the right. Add 0s to the empty space on the left. For negative numbers, this means that they will be converted to positive.

Some examples:

int a = -3; //      1111...11011 
int b = 5; //       0000...00101
int c = a << 1; //  1111...10110
int d = b << 2; //  0000...10100
int e = a >> 2; //  1111...11110
int f = b >> 2; //  0000...00001
int g = a >>> 2; // 0011...11110
Enter fullscreen mode Exit fullscreen mode

Top comments (0)