fork download
  1. #include <iostream>
  2. #include <climits>
  3. #include <stdexcept>
  4. #include <cassert>
  5.  
  6. class bitbuffer {
  7. char buffer;
  8. char held_bits;
  9. public:
  10. bitbuffer() :held_bits(0), buffer(0) {}
  11. unsigned long long read(unsigned char bits) {
  12. unsigned long long result = 0;
  13. //if the buffer doesn't hold enough bits
  14. while (bits > held_bits) {
  15. //grab the all bits in the buffer
  16. bits -= held_bits;
  17. result |= ((unsigned long long)buffer) << bits;
  18. //reload the buffer
  19. if (!std::cin)
  20. throw std::runtime_error("");
  21. std::cin.get(buffer);
  22. held_bits = (char)std::cin.gcount() * CHAR_BIT;
  23. }
  24. //append the bits left to the end of the result
  25. result |= buffer >> (held_bits-bits);
  26. //remove those bits from the buffer
  27. held_bits -= bits;
  28. buffer &= (1ull<<held_bits)-1;
  29. return result;
  30. };
  31. };
  32.  
  33. int main() {
  34. std::cout << "enter 65535: ";
  35. bitbuffer reader; //0x3635353335
  36. assert(reader.read(4) == 0x3);
  37. assert(reader.read(4) == 0x6);
  38. assert(reader.read(8) == 0x35);
  39. assert(reader.read(1) == 0x0);
  40. assert(reader.read(1) == 0x0);
  41. assert(reader.read(1) == 0x1);
  42. assert(reader.read(1) == 0x1);
  43. assert(reader.read(4) == 0x5);
  44. assert(reader.read(16) == 0x3335);
  45. assert(reader.read(8) == 0x0A);
  46. std::cout << "enter FFFFFFFF: ";
  47. assert(reader.read(64) == 0x4646464646464646ull);
  48. std::cout << "PASS!";
  49. return 0;
  50. }
  51.  
Success #stdin #stdout 0.01s 2692KB
stdin
65535
FFFFFFFF
stdout
enter 65535: enter FFFFFFFF: PASS!