C++ Bitwise Operators

C++ provides a set of bitwise operators, which allow you to manipulate the individual bits within an operand. These operators are often used for low-level programming or for optimization purposes. In this article, we'll go over the bitwise operators available in C++, along with examples to illustrate how they work.

OperatorNameDescriptionExample
&ANDPerforms bitwise AND operation between two operands(A & B) returns 12, which is 0000 1100
|ORPerforms bitwise OR operation between two operands(A | B) returns 61, which is 0011 1101
^XORPerforms bitwise XOR operation between two operands(A ^ B) returns 49, which is 0011 0001
~NOTPerforms bitwise NOT operation on the operand(~A ) returns -61, which is 1100 0011 in 2's complement form
<<Left ShiftShifts bits of the operand to the left by specified number of bits(A << 2) returns 240, which is 1111 0000
>>Right ShiftShifts bits of the operand to the right by specified number of bits(A >> 2) returns 15, which is 0000 1111

Here are some examples to illustrate how the bitwise operators can be used in C++ code.

1#include <iostream> 2 3int main() { 4 int x = 7, y = 4; 5 6 std::cout << (x & y) << std::endl; // Output: 4 7 std::cout << (x | y) << std::endl; // Output: 7 8 std::cout << (x ^ y) << std::endl; // Output: 3 9 std::cout << (~x) << std::endl; // Output: -8 10 std::cout << (x << 2) << std::endl; // Output: 28 11 std::cout << (x >> 2) << std::endl; // Output: 1 12 13 return 0; 14}

In these examples, we perform various bitwise operations on the values 7 and 4. You can see how the results of the operations match the descriptions in the table.