Created
September 10, 2015 10:58
-
-
Save MatthewBarker/32f8f2f4660854a0b417 to your computer and use it in GitHub Desktop.
Wrapper for node's buffer allowing writing / reading of individual bits
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
function BitBuffer(size) { | |
size = Math.ceil(size / 8); | |
this.buffer = new Buffer(size); | |
this.buffer.fill(0); | |
} | |
BitBuffer.prototype = { | |
set: function (index, bool) { | |
var pos = index >>> 3; | |
if (bool) { | |
this.buffer[pos] |= 1 << (index % 8); | |
} else { | |
this.buffer[pos] &= ~(1 << (index % 8)); | |
} | |
}, | |
get: function (index) { | |
return (this.buffer[index >>> 3] & (1 << (index % 8))) !== 0; | |
}, | |
flip: function (index) { | |
this.buffer[index >>> 3] ^= 1 << (index % 8); | |
}, | |
writeBinaryString(value, offset) { | |
var bits = value.split(''); | |
offset = offset || 0; | |
bits.forEach(function (bit, index) { | |
this.set(index + offset, bit === '1') | |
}, this); | |
}, | |
readBinaryString(offset, length) { | |
var result = ''; | |
for (; offset < length; offset++) { | |
result += this.get(offset) ? '1' : '0'; | |
} | |
return result; | |
} | |
}; | |
module.exports = BitBuffer; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment