What Are Bitwise Operators?
Bitwise operators are used to perform
operations at the bit level. It works with integer
types (byte, short, int, long). When a bitwise
operation is performed, each bit of the
particular number is treated as an individual
based on the operation.
Eg: 0101 – bit value of 5
Bitwise operators in Java:
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise Complement (NOT
<< Left Shift
>> Signed Right Shift
>>> Unsigned Right Shift
1. Bitwise AND (&)
• This operator is a binary operator, denoted by
'&.' It returns bit by bit AND of input values, i.e.,
if both bits are 1, it gives 1, else it shows 0.
Example:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
Bitwise AND Operation of 5 and 7
0101
& 0111
________
0101 = 5 (In decimal)
2. Bitwise OR (|)
• This operator is a binary operator, denoted by '|'. It
returns bit by bit OR of input values, i.e., if either
of the bits is 1, it gives 1, else it shows 0.
Example:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
Bitwise OR Operation of 5 and 7
0101
| 0111
________
0111 = 7 (In decimal)
3. Bitwise XOR (^)
• This operator is a binary operator, denoted by '^.' It
returns bit by bit XOR of input values, i.e., if
corresponding bits are different, it gives 1, else it
shows 0.
Example:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
Bitwise XOR Operation of 5 and 7
0101
^ 0111
________
0010 = 2 (In decimal)
4. Bitwise Complement (~)
• The unary bitwise complement operator (~)
inverts the bit pattern of an operand. It
converts 0 as 1 and 1 as 0. “(~N+1 = -N)”
Example:
a = 5 = 0101 (In Binary)
Bitwise Complement Operation of 5 in java (8 bits)
~ 00000101
________
11111010 = -6 (In decimal)
Bitwise Shift Operators
Name of operator Sign Description
Signed Left Shift << The left shift operator moves all bits by a given number
of bits to the left.
Signed Right Shift >> The right shift operator moves all bits by a given number
of bits to the right.
Unsigned Right Shift >>> It is the same as the signed right shift, but the vacant
leftmost position is filled with 0 instead of the sign bit.
Left Shift Operator
• The left shift means that shift each of the bits is
in binary representation toward the left.
• Syntax:
x << n
Here, x: an integer n: a non-negative integer
Signed Right Shift Operator
• The Right Shift Operator moves the bits of a
number in a given number of places to the right.
• The >> sign represents the right shift operator.
• When we shift a number to the right, the least
significant bits (rightmost) are deleted, and the
sign bit (0 or 1) is filled in the most considerable
place (leftmost).
• Syntax:
x >> n
Unsigned Right Shift Operator
• Unsigned Right Shift Operator moves the bits of
the integer a given number of places to the
right. The sign bit was filled with 0s. The
Bitwise Zero Fill Right Shift Operator is
represented by the symbol >>>.
• Syntax:
x >>> n