bitbuffer.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include "bitbuffer.h"
  2. #include <memory.h>
  3. #include <stdlib.h>
  4. BitBuffer::BitBuffer()
  5. {
  6. buffer=0;
  7. length=0;
  8. bits=0;
  9. }
  10. void BitBuffer::WriteBit(char bit)
  11. {
  12. if (bits == 0)
  13. Resize(length+1);
  14. bit = !!bit;
  15. unsigned char mask = 1 << (7-bits);
  16. buffer[length-1] &= ~mask;
  17. buffer[length-1] |= (bit << (7-bits));
  18. bits=(bits+1)%8;
  19. }
  20. void BitBuffer::Resize(size_t newlen)
  21. {
  22. if (newlen > length)
  23. {
  24. unsigned char *new_buffer = (unsigned char *)realloc(buffer, newlen);
  25. if (new_buffer)
  26. {
  27. buffer = new_buffer;
  28. memset(buffer+length, 0, newlen-length); // zero out new data
  29. length=newlen;
  30. }
  31. else
  32. {
  33. new_buffer = (unsigned char *)malloc(newlen);
  34. if (new_buffer)
  35. {
  36. memcpy(new_buffer, buffer, length);
  37. free(buffer);
  38. buffer = new_buffer;
  39. memset(buffer+length, 0, newlen-length); // zero out new data
  40. length=newlen;
  41. }
  42. }
  43. }
  44. }
  45. void BitBuffer::WriteBits(uintptr_t num, size_t bitlen)
  46. {
  47. for (size_t i=0;i!=bitlen;i++)
  48. {
  49. WriteBit((num >> (bitlen-i-1))&1);
  50. }
  51. }
  52. void BitBuffer::WriteBytes(void *buffer, size_t bytes)
  53. {
  54. unsigned char *b = (unsigned char *)buffer;
  55. for (size_t i=0;i!=bytes;i++)
  56. WriteBits(b[i], 8);
  57. }
  58. void BitBuffer::WriteByte(unsigned char byte)
  59. {
  60. for (size_t i=0;i!=8;i++)
  61. {
  62. WriteBit((byte >> (7-i))&1);
  63. }
  64. }