1
0

BitReader.cpp 1.8 KB

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