How do I construct and use std::bitset in C++?

In C++, std::bitset is a part of the standard library that is used to represent a fixed-size sequence of bits. It provides an interface for bitwise operations and easy manipulation of bit-level data.

To construct a std::bitset, you need to define the size of the bitset as a template parameter. Optionally, you can initialize it with a string or an unsigned long long integer.

Here’s a simple example of how to construct and use std::bitset:

#include <iostream> #include <bitset> int main() { // Create a bitset of size 8 std::bitset<8> bset1; // All bits initialized to 0 // Set bits at specific positions bset1.set(1); // Set 2nd bit bset1.set(3); // Set 4th bit // Display the bitset std::cout << "Bitset 1: " << bset1 << std::endl; // Output: 00001010 // Create a bitset with initialization std::bitset<8> bset2("10110101"); // Initialize with a binary string // Display the second bitset std::cout << "Bitset 2: " << bset2 << std::endl; // Output: 10110101 // Perform bitwise operations std::bitset<8> bset3 = bset1 & bset2; // AND operation std::cout << "Bitset 1 AND Bitset 2: " << bset3 << std::endl; // Output: 00000000 return 0; }

std::bitset C++ bit manipulation fixed-size bit sequences