fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <bitset>
  4. using namespace std;
  5.  
  6. int main() {
  7. // version using a vetor of bool (1 bit per element)
  8. vector<bool> v;
  9. bool a=1;
  10. bool b=0;
  11. bool c=1;
  12. bool d=0;
  13. v.push_back(a); v.push_back(b); v.push_back(c); v.push_back(d);
  14. // but using/converting vetor<bool> is not so easy
  15. for (int i=0; i<4; i++)
  16. cout << v[i] <<" ";
  17. cout<<endl;
  18.  
  19. // version using a bitset
  20. bitset<8> s;
  21. s[3]=a; // access elements as easily as in an array or a vector
  22. s[2]=b;
  23. s[1]=c;
  24. s[0]=d; // least significant bit (according to the standard)
  25. cout << s<<endl; // streams the bitset as a string of '0' and '1'
  26. cout << "0x"<< hex << s.to_ulong()<<endl; // convert the bitset to unsigned long
  27. cout << s[3] <<endl; // access a specific bit
  28. cout << "Number of bits set: " << s.count()<<endl;
  29.  
  30. bitset<2400> ls;
  31. ls[2201]=true;
  32. return 0;
  33. }
Success #stdin #stdout 0s 4348KB
stdin
Standard input is empty
stdout
1 0 1 0 
00001010
0xa
1
Number of bits set: 2