C++ Standard Library<bitset>

In C++ programming,<bitset>It is part of the standard library and provides a way to manipulate fixed-size bit sets.

A bit set is an array composed of bits, where each bit can be 0 or 1.

<bitset>It provides an efficient way to store and manipulate binary data, especially suitable for scenarios requiring bit-level operations, such as flag management, bit mask operations, etc.

bitsetIt is a template class whose template parameter defines the size of the bit set. For example,bitset<32>it represents a bit set containing 32 bits.

Syntax

The following is usingbitsetBasic syntax:

#include <bitset>

// 声明一个大小为N的bitset
std::bitset<N> b;

// 初始化bitset
b = std::bitset<N>(value);

// 访问位集合中的单个位
bool bit = b[i];

Basic usage of std::bitset

std::bitset is a template class used to represent a fixed-size sequence of binary bits. Its template parameter is the number of bits (N), which indicates the length of the binary sequence.

Define std::bitset:

std::bitset<8> bits;  // 定义一个 8 位的二进制序列

Initialize std::bitset:

  • Default initialization: all bits are0。

  • Initialization from an integer: converts the integer to binary.

  • Initialization from a string: parses the string as binary.

Example

std::bitset<8> bits1;               // Default initialization: 00000000
std::bitset<8> bits2(42);           // Initialize from integer: 00101010
std::bitset<8> bits3("10101010");   // Initialize from string: 10101010

Common member functions

std::bitset provides rich member functions for manipulating binary bits.

Accessing and modifying bits:

  • operator[]: Access or modify a specific bit.

  • set(): Set a specific bit or all bits to1。

  • reset(): Set a specific bit or all bits to0。

  • flip(): Flip a specific bit or all bits.

Example

std::bitset<8> bits("00001111");
bits[0] = 1;          // Modify bit 0: 00001111 -> 00001111
bits.set(4);          // Set bit 4: 00011111 -> 00011111
bits.reset(1);        // Reset bit 1: 00011111 -> 00011101
bits.flip();          // Flip all bits: 00011101 -> 11100010

Querying bit information:

  • count(): returns1the number of.

  • size(): returns the number of bits.

  • test(pos): Check whether a specific bit is1。

  • all(): Check whether all bits are1。

  • any(): Check whether any bit is1。

  • none(): Check whether all bits are0。

Example

std::bitset<8> bits("10101010");
std::cout << "Count of 1s: " << bits.count() << std::endl;  // Output 4
std::cout << "Size: " << bits.size() << std::endl;          // Output 8
std::cout << "Is bit 3 set? " << bits.test(3) << std::endl; // Output 1 (true)
std::cout << "All bits set? " << bits.all() << std::endl;   // Output 0 (false)

Convert to other types:

  • to_ulong(): mapsstd::bitsetConverted tounsigned long。

  • to_ullong(): mapsstd::bitsetConverted tounsigned long long。

  • to_string(): mapsstd::bitsetConvert to string.

Example

std::bitset<8> bits("10101010");
unsigned long num = bits.to_ulong();  // Convert to integer: 170
std::string str = bits.to_string();   // Convert to string: "10101010"

Bitwise operations

std::bitset supports common bit operations, such as bitwise AND, bitwise OR, bitwise XOR, and bitwise NOT.

  • &: bitwise AND

  • |: bitwise OR

  • ^: bitwise XOR

  • ~: bitwise NOT

Example

std::bitset<8> bits1("10101010");
std::bitset<8> bits2("11110000");

std::bitset<8> result_and = bits1 & bits2;  // Bitwise AND: 10100000
std::bitset<8> result_or = bits1 | bits2;   // Bitwise OR: 11111010
std::bitset<8> result_xor = bits1 ^ bits2;  // Bitwise XOR: 01011010
std::bitset<8> result_not = ~bits1;         // Bitwise NOT: 01010101

Example

Basic usage:

Example

#include <iostream>
#include <bitset>

int main() {
    std::bitset<8> b("11001010"); // Initialize from string
    std::cout << "Initial bitset: " << b << std::endl;

    // Access a bit at a specific position
    std::cout << "Bit at position 3: " << b[3] << std::endl;

    // Modify a bit
    b[3] = 1;
    std::cout << "Modified bitset: " << b << std::endl;

    // Flip a bit
    b.flip();
    std::cout << "Flipped bitset: " << b << std::endl;

    return 0;
}

Output result:

Initial bitset: 11001010
Bit at position 3: 0
Modified bitset: 11001011
Flipped bitset: 00110110

Bitwise operations:

Example

#include <iostream>
#include <bitset>

int main() {
    std::bitset<8> b1("10101010");
    std::bitset<8> b2("11110000");

    // Bitwise AND operation
    std::bitset<8> b_and = b1 & b2;
    std::cout << "Bitwise AND: " << b_and << std::endl;

    // Bitwise OR operation
    std::bitset<8> b_or = b1 | b2;
    std::cout << "Bitwise OR: " << b_or << std::endl;

    // Bitwise XOR operation
    std::bitset<8> b_xor = b1 ^ b2;
    std::cout << "Bitwise XOR: " << b_xor << std::endl;

    // Bitwise NOT operation
    std::bitset<8> b_not = ~b1;
    std::cout << "Bitwise NOT: " << b_not << std::endl;

    return 0;
}

Output result:

Bitwise AND: 10100000
Bitwise OR: 11111010
Bitwise XOR: 01111010
Bitwise NOT: 01010101

Iterate over the bitset:

Example

#include <iostream>
#include <bitset>

int main() {
    std::bitset<8> b("10101010");

    // Iterate over the bits in the bitset
    for (size_t i = 0; i < b.size(); ++i) {
        std::cout << b[i];
    }
    std::cout << std::endl;

    return 0;
}

Output result:

10101010

bitsetis a very useful tool in the C++ standard library, allowing programmers to handle bit-level data in an intuitive and efficient way. Through the above examples, we can see how to declare, initialize, access, modify, and perform bit operations. These features are very useful when dealing with binary data or situations requiring bit-level control.

Notes

  • std::bitsetIts size is fixed and determined at compile time.

  • If the number of bits exceedsunsigned longorunsigned long longthe number of bits,to_ulong()andto_ullong()will throwstd::overflow_erroran exception.

  • std::bitsetIt does not support dynamic resizing; if a dynamic bit set is needed, considerstd::vector<bool>。

other extensions