Skip to content
This repository was archived by the owner on Oct 7, 2020. It is now read-only.

buffer: add method readBits for reading slices of a byte #77

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -616,6 +616,21 @@ function checkOffset(offset, ext, length) {
}


Buffer.prototype.readBits = function(position, offset, bitLength, noAssert) {
position = position >>> 0;
offset = offset >>> 0;
bitLength = bitLength >>> 0;
if (!noAssert) {
if (position < 0 || position >= this.length)
throw new RangeError('index out of range');
if (bitLength > 8)
throw new RangeError('bit length out of range');
}

return (this[position] >> offset) & ((1 << bitLength) - 1);
};


Buffer.prototype.readUIntLE = function(offset, byteLength, noAssert) {
offset = offset >>> 0;
byteLength = byteLength >>> 0;
Expand Down
4 changes: 4 additions & 0 deletions test/parallel/test-buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -1172,3 +1172,7 @@ Buffer.poolSize = ps;
assert.throws(function() {
Buffer(10).copy();
});

var b = new Buffer(1).fill(1);
assert.equal(b.readBits(0, 0, 4), 1);
assert.equal(b.readBits(0, 4, 4), 0);