1
0

bitstream.c 998 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include "bitstream.h"
  2. #include <stdlib.h>
  3. #include <string.h>
  4. void bitstream_reader_init(struct bitstream_reader *r, uint8_t *data,
  5. size_t len)
  6. {
  7. memset(r, 0, sizeof(struct bitstream_reader));
  8. r->buf = data;
  9. r->subPos = 0x80;
  10. r->len = len;
  11. }
  12. uint8_t bitstream_reader_read_bit(struct bitstream_reader *r)
  13. {
  14. if (r->pos >= r->len)
  15. return 0;
  16. uint8_t bit = (*(r->buf + r->pos) & r->subPos) == r->subPos ? 1 : 0;
  17. r->subPos >>= 0x1;
  18. if (r->subPos == 0) {
  19. r->subPos = 0x80;
  20. r->pos++;
  21. }
  22. return bit;
  23. }
  24. uint8_t bitstream_reader_read_bits(struct bitstream_reader *r, int bits)
  25. {
  26. uint8_t res = 0;
  27. for (int i = 1; i <= bits; i++) {
  28. res <<= 1;
  29. res |= bitstream_reader_read_bit(r);
  30. }
  31. return res;
  32. }
  33. uint8_t bitstream_reader_r8(struct bitstream_reader *r)
  34. {
  35. return bitstream_reader_read_bits(r, 8);
  36. }
  37. uint16_t bitstream_reader_r16(struct bitstream_reader *r)
  38. {
  39. uint8_t b = bitstream_reader_read_bits(r, 8);
  40. return ((uint16_t)b << 8) | bitstream_reader_read_bits(r, 8);
  41. }