JAVA Syllabus

# Explain different types of bitwise operators?

Bitwise operators are operators that manipulate the bits, or binary digits, of a number. They are used to perform operations such as bit shifting and logical operations on binary values. Here are the different types of bitwise operators:

1. Bitwise AND (&):
The bitwise AND operator compares each bit of two numbers and produces a result that has a 1 in each bit position where both operands have a 1. For example:

``````x = 10110101
y = 11001100
------------------
x & y = 10000100
``````
``` ```
2. Bitwise OR (|):
The bitwise OR operator compares each bit of two numbers and produces a result that has a 1 in each bit position where either operand has a 1. For example:

``````x = 10110101
y = 11001100
------------------
x | y = 11111101``````
``` ```
3. Bitwise XOR (^):
The bitwise XOR operator compares each bit of two numbers and produces a result that has a 1 in each bit position where the operands have different values. For example:

``````x = 10110101
y = 11001100
------------------
x ^ y = 01111001``````
``` ```
4. Bitwise NOT (~):
The bitwise NOT operator inverts each bit of a number, changing each 0 to a 1 and each 1 to a 0. For example:

``````x = 10110101
------------------
~x = 01001010

if x = 10 = 0000 1010
Then,
~x = 1111 0101 (This is nothing but -11 in decimal).
So, ~x = -11.``````
``` ```
5. Left shift (<<):
The left shift operator shifts the bits of a number to the left by a specified number of positions, adding zeros to the right side. For example:

 x = 10110101 -------------x << 2 = 11010100x<<2 means shifting bits towards the left 2 times and adding 2 zeros to the right side.
``` ```
6. Right shift (>>):
The right shift operator shifts the bits of a number to the right by a specified number of positions, adding zeros to the left side. For example:

 x = 10110101 -------------x >> 2 = 00101101x>>2 means shifting bits towards the right 2 times and adding 2 zeros to the left side.
7.  Bitwise Zero fill Right shift (>>>):
The ">>>" operator, on the other hand, performs an unsigned right shift, which means that it always shifts in 0's on the left-hand side, regardless of the sign of the value being shifted. This operator is often used for bit manipulation and is useful when you want to ignore the sign bit and treat the shifted value as a non-negative number.

``````int x = -8; // binary: 11111111111111111111111111111000
System.out.println(x >>> 2); // output: 1073741822 (binary: 00111111111111111111111111111110)
``````

These bitwise operators are commonly used in computer programming for tasks such as encoding and decoding data, bitwise arithmetic, and creating bit masks.

03/03/2023, 12:53 pm Read : 80 times