简体   繁体   中英

working of std::bitset in cpp

I want to know how is this program working:

 #include <bitset> #include <iostream> const int option_1 = 0; const int option_2 = 1; const int option_3 = 2; const int option_4 = 3; const int option_5 = 4; const int option_6 = 5; const int option_7 = 6; const int option_8 = 7; int main() { std::bitset<8> bits(0x2); bits.set(option_5); bits.flip(option_6); bits.reset(option_6); std::cout << "Bit 4 has value: " << bits.test(option_5) << '\\n'; std::cout << "Bit 5 has value: " << bits.test(option_6) << '\\n'; std::cout << "All the bits: " << bits << '\\n'; return 0; } 

I have seen this example on a website, But cannot understand the working of some part of this program.
here, first option5 is set to 4, then in main program "bit.set(option5);" is used to set it to 1(is what i think). then what is use of that 4 assigned to integer option5 above??

So this is basically at a high level an array of bits. Using non type templating an array of bits is created on the stack.

The option5 variable is used to set the fourth bit (from the back when printed) to 1. So when you print out the values there is a 1 in the location pointed to by option5 which is location 4 from the back.

The constructor of the bitset is used to initialize the bitset to look like 0b00000010. The set() function sets the bit at the location specified to 1, the reset() function sets the bit at the location specified to 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM