BitReader.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. #include "BitReader.h"
  2. static uint32_t mask[8]=
  3. {
  4. 0x1,
  5. 0x3,
  6. 0x7,
  7. 0xF,
  8. 0x1F,
  9. 0x3F,
  10. 0x7F,
  11. 0xFF
  12. };
  13. static uint32_t msk[33] =
  14. {
  15. 0x00000000,0x00000001,0x00000003,0x00000007,
  16. 0x0000000f,0x0000001f,0x0000003f,0x0000007f,
  17. 0x000000ff,0x000001ff,0x000003ff,0x000007ff,
  18. 0x00000fff,0x00001fff,0x00003fff,0x00007fff,
  19. 0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  20. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,
  21. 0x00ffffff,0x01ffffff,0x03ffffff,0x07ffffff,
  22. 0x0fffffff,0x1fffffff,0x3fffffff,0x7fffffff,
  23. 0xffffffff
  24. };
  25. void BitReader::alignbyte()
  26. {
  27. flushbits(numBits&7);
  28. }
  29. void BitReader::getbytes(void *data, uint32_t n)
  30. {
  31. memcpy(data, this->data, n);
  32. flushbits(n*8);
  33. }
  34. uint8_t BitReader::getbits1()
  35. {
  36. uint8_t byte = data[0];
  37. uint32_t count = (numBits-1) & 7;
  38. byte &= mask[count];
  39. byte >>= count;
  40. numBits--;
  41. if ((numBits % 8) == 0)
  42. data++;
  43. return byte;
  44. }
  45. uint32_t BitReader::getbits(uint32_t n)
  46. {
  47. uint32_t val = showbits(n);
  48. flushbits(n);
  49. return val;
  50. }
  51. uint8_t BitReader::showbits1() const
  52. {
  53. uint8_t byte = data[0];
  54. uint32_t count = (numBits-1) & 7;
  55. byte &= mask[count];
  56. byte >>= count;
  57. return byte;
  58. }
  59. uint32_t BitReader::showbits(uint32_t n) const
  60. {
  61. uint32_t val;
  62. switch((numBits+7) >> 3)
  63. {
  64. case 0:
  65. return 0;
  66. case 1:
  67. val=(data[0]<<24);
  68. break;
  69. case 2:
  70. val=(data[0]<<24) | (data[1]<<16);
  71. break;
  72. case 3:
  73. val=(data[0]<<24) | (data[1]<<16) | (data[2]<<8);
  74. break;
  75. default:
  76. val=(data[0]<<24) | (data[1]<<16) | (data[2]<<8) | data[3];
  77. break;
  78. }
  79. uint32_t c = ((numBits-1) & 7) + 25;
  80. return (val>>(c-n)) & msk[n];
  81. }
  82. void BitReader::flushbits(uint32_t n)
  83. {
  84. uint32_t oldpos = (numBits+7)>>3;
  85. numBits-=n;
  86. uint32_t newpos = (numBits+7)>>3;
  87. data += (oldpos - newpos);
  88. }
  89. bool BitReader::empty()
  90. {
  91. return numBits==0;
  92. }
  93. uint32_t BitReader::size() const
  94. {
  95. return numBits;
  96. }