bitstream.c 992 B

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