Home C++ C++ Standard Template Library (STL) bitset tutorial

C++ Standard Template Library (STL) bitset tutorial

The bitset in the C++ Standard Template Library (STL) is a container that represents a fixed-size sequence of bits (binary values) as 0s and 1s.

It provides an efficient way to handle binary data and perform bitwise operations on them.

Key Features of bitset

  1. Fixed-size: Size is specified at compile time and cannot be changed.
  2. Binary operations: Supports various bitwise operations like AND, OR, XOR, and NOT.
  3. Efficient: Uses minimal memory to represent large numbers of bits.

Basic Syntax of bitset

#include <bitset>
using namespace std;

bitset<N> bits; // where N is the number of bits

Let’s go through several examples to understand the usage and functionality of bitset.

1. Initializing a bitset

A bitset can be initialized in various ways, including using integers, strings, or directly as binary.

#include <iostream>
#include <bitset>
using namespace std;

int main() {
    // Initialize with integer
    bitset<8> bits1(42);         // Binary representation of 42: 00101010
    cout << "bits1: " << bits1 << endl;

    // Initialize with binary string
    bitset<8> bits2(string("10101010"));
    cout << "bits2: " << bits2 << endl;

    // Default initializes to 0
    bitset<8> bits3;
    cout << "bits3: " << bits3 << endl;

    return 0;
}

Output:

bits1: 00101010
bits2: 10101010
bits3: 00000000

2. Accessing Bits

bitset provides functions to access and manipulate individual bits. You can use [] for direct access or test to check the value of a specific bit.

#include <iostream>
#include <bitset>
using namespace std;

int main() {
    bitset<8> bits("10101010");

    // Accessing bits
    cout << "Bit at position 2: " << bits[2] << endl;
    cout << "Bit at position 3: " << bits[3] << endl;

    // Test if a specific bit is set
    if (bits.test(4)) {
        cout << "Bit at position 4 is set." << endl;
    } else {
        cout << "Bit at position 4 is not set." << endl;
    }

    return 0;
}

Output:

Bit at position 2: 1
Bit at position 3: 0
Bit at position 4 is set.

3. Setting and Resetting Bits

You can set, reset, and toggle specific bits, or apply these operations to all bits at once.

#include <iostream>
#include <bitset>
using namespace std;

int main() {
    bitset<8> bits;

    // Set specific bits
    bits.set(1);
    bits.set(4);
    cout << "After setting bits at positions 1 and 4: " << bits << endl;

    // Reset specific bits
    bits.reset(4);
    cout << "After resetting bit at position 4: " << bits << endl;

    // Toggle specific bit
    bits.flip(1);
    cout << "After toggling bit at position 1: " << bits << endl;

    // Set all bits
    bits.set();
    cout << "After setting all bits: " << bits << endl;

    // Reset all bits
    bits.reset();
    cout << "After resetting all bits: " << bits << endl;

    return 0;
}

Output:

After setting bits at positions 1 and 4: 00010010
After resetting bit at position 4: 00000010
After toggling bit at position 1: 00000000
After setting all bits: 11111111
After resetting all bits: 00000000

4. Counting Set and Unset Bits

The count function returns the number of set bits (1s) in a bitset, and size returns the total number of bits.

#include <iostream>
#include <bitset>
using namespace std;

int main() {
    bitset<8> bits("10110110");

    cout << "Number of set bits: " << bits.count() << endl;
    cout << "Number of unset bits: " << bits.size() - bits.count() << endl;

    return 0;
}

Output:

Number of set bits: 5
Number of unset bits: 3

5. Bitwise Operations

bitset supports bitwise operations like AND, OR, XOR, and NOT.

#include <iostream>
#include <bitset>
using namespace std;

int main() {
    bitset<8> bits1("11001010");
    bitset<8> bits2("10110100");

    cout << "bits1: " << bits1 << endl;
    cout << "bits2: " << bits2 << endl;

    cout << "bits1 AND bits2: " << (bits1 & bits2) << endl;
    cout << "bits1 OR bits2: " << (bits1 | bits2) << endl;
    cout << "bits1 XOR bits2: " << (bits1 ^ bits2) << endl;
    cout << "NOT bits1: " << (~bits1) << endl;

    return 0;
}

Output:

bits1: 11001010
bits2: 10110100
bits1 AND bits2: 10000000
bits1 OR bits2: 11111110
bits1 XOR bits2: 01111110
NOT bits1: 00110101

6. Converting bitset to Other Formats

You can convert a bitset to an integer or a string.

#include <iostream>
#include <bitset>
using namespace std;

int main() {
    bitset<8> bits("1101");

    // Convert to integer
    unsigned long num = bits.to_ulong();
    cout << "Integer representation: " << num << endl;

    // Convert to string
    string str = bits.to_string();
    cout << "String representation: " << str << endl;

    return 0;
}

Output:

Integer representation: 13
String representation: 00001101

7. Checking if Any or None of the Bits are Set

any checks if at least one bit is set, and none checks if all bits are unset.

#include <iostream>
#include <bitset>
using namespace std;

int main() {
    bitset<8> bits1("00000000");
    bitset<8> bits2("10100000");

    cout << "bits1 - Any set? " << (bits1.any() ? "Yes" : "No") << endl;
    cout << "bits1 - None set? " << (bits1.none() ? "Yes" : "No") << endl;

    cout << "bits2 - Any set? " << (bits2.any() ? "Yes" : "No") << endl;
    cout << "bits2 - None set? " << (bits2.none() ? "Yes" : "No") << endl;

    return 0;
}

Output:

bits1 - Any set? No
bits1 - None set? Yes
bits2 - Any set? Yes
bits2 - None set? No

8. Iterating Over Bits

Although bitset doesn’t provide direct iterators, you can iterate over bits by accessing them through indices.

#include <iostream>
#include <bitset>
using namespace std;

int main() {
    bitset<8> bits("10101010");

    cout << "Bits: ";
    for (size_t i = 0; i < bits.size(); ++i) {
        cout << bits[i] << " ";
    }
    cout << endl;

    return 0;
}

Output:

Bits: 0 1 0 1 0 1 0 1 

9. Checking Equality and Inequality Between bitsets

Two bitsets can be compared using == and != operators.

#include <iostream>
#include <bitset>
using namespace std;

int main() {
    bitset<8> bits1("10101010");
    bitset<8> bits2("10101010");
    bitset<8> bits3("11001100");

    cout << "bits1 == bits2: " << (bits1 == bits2) << endl;
    cout << "bits1 != bits3: " << (bits1 != bits3) << endl;

    return 0;
}

Output:

bits1 == bits2: 1
bits1 != bits3: 1

10. Using bitset as a Simple Flag Manager

A bitset can act as a simple flag manager where each bit represents a different flag.

#include <iostream>
#include <bitset>
using namespace std;

int main() {
    bitset

<4> flags; // Four flags (all initially 0)

    // Setting specific flags
    flags.set(0); // Enable flag 0
    flags.set(2); // Enable flag 2

    cout << "Flags: " << flags << endl;

    // Checking if specific flags are enabled
    cout << "Is flag 0 set? " << (flags.test(0) ? "Yes" : "No") << endl;
    cout << "Is flag 1 set? " << (flags.test(1) ? "Yes" : "No") << endl;

    return 0;
}

Output:

Flags: 0101
Is flag 0 set? Yes
Is flag 1 set? No

Summary Table of bitset Operations

Operation Code Example Description
Initialize with integer bitset<8> bits(42); Initializes bitset with an integer
Initialize with binary string bitset<8> bits(“1010”); Initializes bitset with a binary string
Access bit bits[i]; or bits.test(i); Accesses specific bit by index
Set specific bit bits.set(i); Sets bit at index i to 1
Reset specific bit bits.reset(i); Sets bit at index i to 0
Toggle specific bit bits.flip(i); Flips (inverts) the bit at index i
Count set bits bits.count(); Returns the number of bits set to 1
Check any bit set bits.any(); Checks if at least one bit is set
Check all bits unset bits.none(); Checks if all bits are unset
Convert to integer bits.to_ulong(); Converts bitset to an unsigned long
Convert to string bits.to_string(); Converts bitset to a string
Bitwise AND bits1 & bits2; Performs bitwise AND on two bitsets
Bitwise OR `bits1 bits2;`
Bitwise XOR bits1 ^ bits2; Performs bitwise XOR on two bitsets
Bitwise NOT ~bits1; Inverts all bits in a bitset
Equality check bits1 == bits2; Checks if two bitsets are equal

Complete Example

This example uses bitset to perform various binary operations and conversions, simulating a basic binary calculator.

#include <iostream>
#include <bitset>
using namespace std;

int main() {
    bitset<8> num1("10101010");
    bitset<8> num2("11001100");

    cout << "Number 1: " << num1 << endl;
    cout << "Number 2: " << num2 << endl;

    cout << "AND: " << (num1 & num2) << endl;
    cout << "OR: " << (num1 | num2) << endl;
    cout << "XOR: " << (num1 ^ num2) << endl;
    cout << "NOT num1: " << (~num1) << endl;

    // Convert num1 to integer
    unsigned long num1Int = num1.to_ulong();
    cout << "Integer representation of num1: " << num1Int << endl;

    return 0;
}

Sample Output:

Number 1: 10101010
Number 2: 11001100
AND: 10001000
OR: 11101110
XOR: 01100110
NOT num1: 01010101
Integer representation of num1: 170

Key Takeaways

  • bitset is a powerful container for handling binary data with fixed-size sequences of bits.
  • It supports bitwise operations, conversions to integers and strings, and bit manipulation functions like set, reset, flip, and test.

You may also like