How is the bitset used in c++?
In C++, std::bitset is a class for handling bit operations that can store and manipulate fixed-length sequences of bits.
Here is how to use std::bitset:
- Include header file: First of all, in order to use std::bitset, you need to include the header file.
- Creating objects: std::bitset objects can be created in the following ways:
std::bitset var; // Creates a bitset object of length N, with all bits set to 0 by default
std::bitset var(value); // Creates a bitset object of length N and initializes it to the given integer value
std::bitset var(string); // Creates a bitset object of length N and initializes it with the given binary string - Among them, N represents the length of the bitset.
- Accessing and modifying bits: you can use the [] operator to access and modify bits in a bitset.
var[pos] = value; // set bit at position ‘pos’ to ‘value’
value = var[pos]; // get the value of bit at position ‘pos’ - Member functions: std::bitset also provides some member functions for performing bit operations, as follows:
- size(): Returns the length of the bitset.
- count(): returns the number of bits that have been set to 1 in the bitset.
- any(): Checks if at least one bit is set to 1 in the bitset.
- none() function checks if all bits in the bitset are set to 0.
- all(): Checks if all bits in the bitset are set to 1.
- flip(): invert all bits in the bitset.
- reset(): reset all bits in the bitset to 0.
- set(): sets all bits in the bitset to 1.
- Check if the bit at position pos is set to 1.
- Bitwise operations: std::bitset also supports bitwise operators such as AND, OR, XOR, etc. as shown below:
- ” &: Bitwise AND operator.”
- Bitwise OR operator.
- ^: Bitwise XOR operator.
- ~: Bitwise NOT operator.
- You can convert it to a binary string using the to_string() function of the std::bitset object, or output it using the cout output operator of the std::bitset object.
The code example is shown below:
#include <bitset>
#include <iostream>
int main() {
std::bitset<8> bits; // 创建一个长度为8的bitset对象,默认所有位都设置为0
std::cout << bits << std::endl; // 输出: 00000000
bits.set(3); // 将位3设置为1
std::cout << bits << std::endl; // 输出: 00001000
bits.flip(); // 翻转所有位
std::cout << bits << std::endl; // 输出: 11110111
bits.reset(); // 将所有位重置为0
std::cout << bits << std::endl; // 输出: 00000000
return 0;
}
The above code creates a bitset object with a length of 8, performs some operations on its bits, and prints the results.