diff --git a/lib/buffer.js b/lib/buffer.js index 1b9c68465..9b7af8a42 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -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; diff --git a/test/parallel/test-buffer.js b/test/parallel/test-buffer.js index 1d0214873..02c50d30f 100644 --- a/test/parallel/test-buffer.js +++ b/test/parallel/test-buffer.js @@ -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);