1// Instantiating and printing a bitset
2
3#include <iostream>
4#include <bitset>
5
6int main() {
7 // A bitset. The size must be able to be determined
8 // at compile time.
9 //
10 // The bitset can be set using a number or a string
11 std::bitset<8> byte1 = bitset<8>(97);
12 std::bitset<8> byte2 = bitset<8>("0001101")
13
14 std::cout << byte1; // Output: 01100001
15}
1< Bitset > The C++ standard library also provides the bitset structure, which
2corresponds to an array whose each value is either 0 or 1.
3
4 string s1 = bitset<8>(6).to_string(); //convert number to binary string
5 cout<<s1<<endl; //00000110
6 string s2 = "110010";
7 bitset<8> b1(s2); // [0, 0, 1, 1, 0, 0, 1, 0]
8 cout << b1.count(); //3
1// constructing bitsets
2#include <iostream> // std::cout
3#include <string> // std::string
4#include <bitset> // std::bitset
5
6int main ()
7{
8 std::bitset<16> foo;
9 std::bitset<16> bar (0xfa2);
10 std::bitset<16> baz (std::string("0101111001"));
11
12 std::cout << "foo: " << foo << '\n';
13 std::cout << "bar: " << bar << '\n';
14 std::cout << "baz: " << baz << '\n';
15
16 return 0;
17}