Bitwise Operators
Bitwise operators are used to perform operations on values or variables, one bit at a time.
What is a Bitwise Operator?
A bitwise operator is a symbol or keyword that tells the computer what operation to perform, bit by bit, on values or variables.
See this page for an overview of other types of operators.
The most common bitwise operators are:
&
(Bitwise AND)|
(Bitwise OR)^
(Bitwise XOR)~
(Bitwise NOT)<<
(Left shift)>>
(Right shift)
All data in the computer is stored as sequences of 0
s and 1
s. This makes it possible to use bitwise operators to manipulate the data.
Use the simulation below to click around and see the result of different bitwise operators:
Bitwise AND
result = a & b
a
00001011
11
operator
&
b
00000111
7
result
00000000
0
In the simulation above, the rightmost column shows the decimal values of the variables a
, b
, and result
. The decimal numbers are displayed to give a better understanding of what happens if you do the operation 11 & 7
(using decimal numbers), and why the result is 3
.
Left shift <<
, and right shift >>
operators shift the bits of variable a
to the left or right. The number of positions to shift is specified by second variable b
, that is why variable b
is limited to the first 2 bits in the simulation above.
In the example below, we use the bitwise OR operator |
to combine two variables stored in binary format:
a = 0b1010
b = 0b0110
result = a | b
print(bin(result))
const a = 0b1010;
const b = 0b0110;
const result = a | b;
console.log(result.toString(2));
int a = 0b1010;
int b = 0b0110;
int result = a | b;
System.out.println(Integer.toBinaryString(result));
int a = 0b1010;
int b = 0b0110;
int result = a | b;
cout << bitset<4>(result);
Run Example »