fork download
  1. #include <climits>
  2. #include <iostream>
  3. #include <cassert>
  4.  
  5. template<int S> struct boolset {
  6. static int const SIZE = ((S / CHAR_BIT) + (0 != (S % CHAR_BIT)));
  7. unsigned char m_bits[SIZE];
  8. public:
  9. boolset() : m_bits() { for(int i = 0; i < SIZE; ++i) m_bits[i] = 0; }
  10.  
  11. bool get(int i) const {
  12. assert(i < S);
  13. return (m_bits[i / CHAR_BIT] & (1 << (i % CHAR_BIT)));
  14. }
  15.  
  16. void set(int i, bool v) {
  17. assert(i < S);
  18. if(v) { m_bits[i / CHAR_BIT] |= (1 << (i % CHAR_BIT)); }
  19. else { m_bits[i / CHAR_BIT] &= ~(1 << (i % CHAR_BIT)); }
  20. }
  21.  
  22. void print(std::ostream & s) const {
  23. for(int i = 0; i < S; ++i) {
  24. s << get(i);
  25. }
  26. }
  27. };
  28.  
  29. int main(int argc, char ** argv) {
  30. std::cout << sizeof(boolset<1>) << std::endl;
  31. std::cout << sizeof(boolset<8>) << std::endl;
  32. std::cout << sizeof(boolset<9>) << std::endl;
  33. std::cout << sizeof(boolset<16>) << std::endl;
  34. std::cout << sizeof(boolset<17>) << std::endl;
  35. std::cout << sizeof(boolset<32>) << std::endl;
  36. std::cout << sizeof(boolset<33>) << std::endl;
  37. std::cout << sizeof(boolset<64>) << std::endl;
  38. std::cout << sizeof(boolset<129>) << std::endl;
  39. std::cout << std::endl;
  40. boolset<31> bs;
  41. bs.set(0, true);
  42. bs.set(28, true);
  43. bs.set(2, true);
  44. std::cout << bs.get(28) << std::endl;
  45. bs.print(std::cout); std::cout << std::endl;
  46. bs.set(2, false);
  47. bs.print(std::cout); std::cout << std::endl;
  48. }
Success #stdin #stdout 0s 2852KB
stdin
Standard input is empty
stdout
1
1
2
2
3
4
5
8
17

1
1010000000000000000000000000100
1000000000000000000000000000100