Basic Bitwise Operations

Basic Bitwise Operators in C++

BeginnerTopic: Bitwise Operations Programs
Back

C++ Basic Bitwise Operations Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
#include <bitset>
using namespace std;

void printBinary(int num) {
    cout << bitset<8>(num) << " (" << num << ")" << endl;
}

int main() {
    int a = 12;  // 00001100
    int b = 25;  // 00011001
    
    cout << "a = ";
    printBinary(a);
    cout << "b = ";
    printBinary(b);
    cout << endl;
    
    // Bitwise AND
    int andResult = a & b;
    cout << "a & b (AND) = ";
    printBinary(andResult);
    
    // Bitwise OR
    int orResult = a | b;
    cout << "a | b (OR) = ";
    printBinary(orResult);
    
    // Bitwise XOR
    int xorResult = a ^ b;
    cout << "a ^ b (XOR) = ";
    printBinary(xorResult);
    
    // Bitwise NOT
    int notResult = ~a;
    cout << "~a (NOT) = ";
    printBinary(notResult);
    
    // Left shift
    int leftShift = a << 2;
    cout << "a << 2 (Left shift) = ";
    printBinary(leftShift);
    
    // Right shift
    int rightShift = a >> 2;
    cout << "a >> 2 (Right shift) = ";
    printBinary(rightShift);
    
    return 0;
}
Output
a = 00001100 (12)
b = 00011001 (25)

a & b (AND) = 00001000 (8)
a | b (OR) = 00011101 (29)
a ^ b (XOR) = 00010101 (21)
~a (NOT) = 11110011 (243)
a << 2 (Left shift) = 00110000 (48)
a >> 2 (Right shift) = 00000011 (3)

Understanding Basic Bitwise Operations

Bitwise operators work on individual bits. AND (&): 1 if both bits are 1. OR (|): 1 if either bit is 1. XOR (^): 1 if bits are different. NOT (~): inverts all bits. Left shift (<<): multiplies by 2^n. Right shift (>>): divides by 2^n. Useful for flags, masks, and low-level operations.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents