fork download
  1. #include <iostream>
  2. #include <bitset>
  3.  
  4. template <size_t N> class BitVector
  5. {
  6. private:
  7.  
  8. std::bitset<N> _data;
  9.  
  10. public:
  11.  
  12. BitVector (unsigned long num) : _data (num) { };
  13. BitVector (const std::string& str) : _data (str) { };
  14.  
  15. template <size_t M>
  16. std::bitset<M> getBits (size_t selIdx)
  17. {
  18. std::bitset<M> retBitset;
  19. for (size_t idx = 0; idx < M; ++idx)
  20. {
  21. retBitset |= (_data[M * selIdx + idx] << (M - 1 - idx));
  22. }
  23. return retBitset;
  24. }
  25.  
  26. template <size_t M>
  27. void setBits (size_t selIdx, uint8_t num)
  28. {
  29. const unsigned char* curByte = reinterpret_cast<const unsigned char*> (&num);
  30. for (size_t bitIdx = 0; bitIdx < 8; ++bitIdx)
  31. {
  32. bool bitSet = (1 == ((*curByte & (1 << (8 - 1 - bitIdx))) >> (8 - 1 - bitIdx)));
  33. _data.set(M * selIdx + bitIdx, bitSet);
  34. }
  35. }
  36.  
  37. void print_7_8()
  38. {
  39. std:: cout << "\n7 bit representation: ";
  40. for (size_t idx = 0; idx < (N / 7); ++idx)
  41. {
  42. std::cout << getBits<7>(idx) << " ";
  43. }
  44. std:: cout << "\n8 bit representation: ";
  45. for (size_t idx = 0; idx < N / 8; ++idx)
  46. {
  47. std::cout << getBits<8>(idx) << " ";
  48. }
  49. }
  50. };
  51.  
  52. int main ()
  53. {
  54. BitVector<56> num = 127;
  55.  
  56. std::cout << "Before changing values...:";
  57. num.print_7_8();
  58.  
  59. num.setBits<8>(0, 0x81);
  60. num.setBits<8>(1, 0b00110011);
  61. num.setBits<8>(2, 0b10010101);
  62. num.setBits<8>(3, 0xAA);
  63. num.setBits<8>(4, 0x81);
  64. num.setBits<8>(5, 0xFF);
  65. num.setBits<8>(6, 0x00);
  66.  
  67. std::cout << "\n\nAfter changing values...:";
  68. num.print_7_8();
  69.  
  70. std::cout << "\n\n8 Bits: " << num.getBits<8>(5) << " to ulong: " << num.getBits<8>(5).to_ulong();
  71. std::cout << "\n7 Bits: " << num.getBits<7>(6) << " to ulong: " << num.getBits<7>(6).to_ulong();
  72.  
  73. num = BitVector<56>(std::string("1001010100000100"));
  74. std::cout << "\n\nAfter changing values...:";
  75. num.print_7_8();
  76.  
  77. return 0;
  78. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Before changing values...:
7 bit representation: 1111111 0000000 0000000 0000000 0000000 0000000 0000000 0000000 
8 bit representation: 11111110 00000000 00000000 00000000 00000000 00000000 00000000 

After changing values...:
7 bit representation: 1000000 1001100 1110010 1011010 1010100 0000111 1111110 0000000 
8 bit representation: 10000001 00110011 10010101 10101010 10000001 11111111 00000000 

8 Bits: 11111111 to ulong: 255
7 Bits: 1111110 to ulong: 126

After changing values...:
7 bit representation: 0010000 0101010 0100000 0000000 0000000 0000000 0000000 0000000 
8 bit representation: 00100000 10101001 00000000 00000000 00000000 00000000 00000000