In the standard template library of C ++, a set of template classes for operating binary bits are provided, which makes the operation bits quite convenient and also facilitates binary operations.
The following is an example of using a function:
# Include <iostream> <br/> # include <bitset> <br/> # include <stdio. h> <br/> int main () <br/>{< br/> STD: String S ("01001"); <br/> STD :: bitset <5> B (s); <br/> STD: bitset <5> B1 (5 ); <br/> // test bitset count function <br/> STD: cout <"bitset B. count = "<B. count () <STD: Endl; <br/> // test bitset operator [] size () <br/> for (INT I = 0; I <B. size (); ++ I) <br/> STD: cout <B [I] <STD: Endl; <br/> // test bitset any () function <br/> STD: cout <"B. any () = "<B. any () <STD: Endl; <br/> // test bitset flip () function <br/> STD: cout <"B. flip = "<B. flip (2) <STD: Endl; <br/> STD: cout <"B. flip = "<B. flip () <STD: Endl; <br/> // test bitset none () function <br/> STD: cout <"B. none = "<B. none () <STD: Endl; <br/> // test bitset reset function <br/> STD: cout <"B. reset = "<B. reset (2) <STD: Endl; <br/> STD: cout <"B. reset = "<B. reset () <STD: Endl; <br/> STD: cout <"B. flip = "<B. flip () <STD: Endl; <br/> // test bitset test function <br/> for (INT I = 0; I <B. size (); ++ I) <br/> STD: cout <"B. test = "<B. test (I) <STD: Endl; <br/> // test bitset to_sting () to_ulong () function <br/> STD: cout <"B. to_string () = "<B. to_string () <STD: Endl; <br/> STD: cout <"b1.to _ ulong () =" <b1.to _ ulong () <STD :: endl; <br/> return 0; <br/>}5, 1 top <br/>
The execution result is as follows:
Bitset B. Count = 2
1
0
0
1
0
B. Any () = 1
B. Flip = 01101.
B. Flip = 10010.
B. None = 0
B. Reset = 10010.
B. Reset = 00000.
B. Flip = 11111.
B. test = 1
B. test = 1
B. test = 1
B. test = 1
B. test = 1
B. to_string () = 11111
B1.to _ ulong () = 5
The following describes the functions:
1. Constructor
Bitset <5> OBJ (5); construct a template instance with a single digit of 5 and a numerical value of 10 to 5.
Bitset <5> strobj (string ("01001"); uses a string to construct a template instance.
2. Count Function
Returns the number of set bits.
3. OPERATOR []
The value corresponding to each single digit is generally 0 or 1.
4. Any Function
Whether all digits are set
5. Flip
Returns the inverse value of the corresponding bitwise value 0 --> 1 1 --> 0.
Flip () indicates the inverse of all digits.
Flip (2) indicates the inverse of the second digit.
6. Reset
Reset () indicates resetting all values
Reset (2) indicates a second reset.
7. None
Not set either.
8. Test
Test (n) checks whether the nth bit has been set
9. Size
Returns the number of digits of the instance.
10. Set
Set (n, 0) to 0
11. to_string
Convert to string
12. to_ulong
Convert to unsigned long integer
This is very effective in operating binary data.
If it is reprinted, please specify the reference source. Thank you !!! (Please respect others' labor achievements)