cpp-operadores-bitwise

Bitwise Operators in C++

  • 5 min

Bitwise operators in C++ allow manipulating data at the bit level, working with individual bits or groups of bits within a variable.

Unlike common arithmetic operators, which operate on complete values, bitwise operators manipulate each bit in the binary representation of a number.

C++ provides several bitwise operators, each with its own specific functionality. Here is a summary table.

OperatorDescription
&Bitwise AND
|Bitwise OR
^Bitwise XOR
~Bitwise NOT
<<Left shift
>>Right shift

Types of bitwise operators in C++

Bitwise AND Operator &

The bitwise AND operator performs a logical AND operation between each corresponding pair of bits of two operands. The result is 1 only if both bits are 1, otherwise the result is 0.

int a = 6;   // Binary: 00000110
int b = 3;   // Binary: 00000011

int result = a & b; // Binary: 00000010 (only the common bits)
Copied!

In this example, the operation a & b compares each bit in numbers a and b. Only the third bit from the right is 1 in both, so the result is 00000010, which equals 2 in decimal.

Bitwise OR Operator |

The bitwise OR operator performs a logical OR operation between each corresponding pair of bits of two operands. The result is 1 if at least one of the bits is 1, otherwise the result is 0.

int a = 6;   // Binary: 00000110
int b = 3;   // Binary: 00000011

int result = a | b; // Binary: 00000111 (if any bit is 1)
Copied!

Here, the operation a | b sets each bit to 1 if at least one of the corresponding bits in a or b is 1. The result is 00000111, which is 7 in decimal.

Bitwise XOR Operator ^

int a = 6;   // Binary: 00000110
int b = 3;   // Binary: 00000011

int result = a ^ b; // Binary: 00000101 (only if the bits are different)
}
Copied!

In this case, a ^ b returns 1 only if the corresponding bits in a and b are different. The result 00000101 equals 5.

Bitwise NOT Operator ~

The bitwise NOT operator performs a bitwise negation of its operand, inverting each bit of the operand (0s become 1s and vice versa).

int a = 6;    // Binary: 00000110

int result = ~a; // Binary: 11111001 in an 8-bit representation
}
Copied!

Left Shift

The << operator shifts all bits to the left. In the example, 3 << 2 is 00001100, which equals 12.

int a = 3;   // Binary: 00000011
int result = a << 2; // Shifts two bits to the left
// Result: 12 (00001100)
}
Copied!

This shift is similar to multiplying the number by powers of 2 (in this case, 3 * 2^2 = 12).

Right Shift

The >> operator shifts bits to the right. In the example, 12 >> 2 is 00000011, which equals 3.

int a = 12;  // Binary: 00001100
int result = a >> 2; // Shifts two bits to the right

// Result: 3 (00000011)
Copied!

This shift is similar to dividing the number by powers of 2 (12 / 2^2 = 3).

Applications of bitwise operators

If you want to delve deeper, here is the binary course👇

Learn the basics of programming with the binary course