bit-buffer.js 715 B

12345678910111213141516171819202122232425262728293031323334353637
  1. function BitBuffer () {
  2. this.buffer = []
  3. this.length = 0
  4. }
  5. BitBuffer.prototype = {
  6. get: function (index) {
  7. var bufIndex = Math.floor(index / 8)
  8. return ((this.buffer[bufIndex] >>> (7 - index % 8)) & 1) === 1
  9. },
  10. put: function (num, length) {
  11. for (var i = 0; i < length; i++) {
  12. this.putBit(((num >>> (length - i - 1)) & 1) === 1)
  13. }
  14. },
  15. getLengthInBits: function () {
  16. return this.length
  17. },
  18. putBit: function (bit) {
  19. var bufIndex = Math.floor(this.length / 8)
  20. if (this.buffer.length <= bufIndex) {
  21. this.buffer.push(0)
  22. }
  23. if (bit) {
  24. this.buffer[bufIndex] |= (0x80 >>> (this.length % 8))
  25. }
  26. this.length++
  27. }
  28. }
  29. module.exports = BitBuffer