buffer: add method readBits for reading slices of a byte
Overview
The readBits method allows for reading bits that might be inside of a byte, most commonly, a nibble. Bits are fairly common in the hardware world and often times a byte can be segmented multiple times. readBits allows you to read the byte and deem valuable information from it. Generally this will only be in the form of an integer value.
Usage
Say I have a buffer, where in position 12, there is a nibble. The first part of the nibble is 9 and the second part is 0.
var buffer = new Buffer('0000000000000000000000000900', 'hex');
buffer.readBits(12, 0, 4); // 9
buffer.readBits(12, 4, 8); // 0
The reason for this, is because it is drastically easier than writing and wiring the following on top of the buffer, which can lead to errors and becomes far more difficult from a readability point of view.
var buffer = new Buffer('0000000000000000000000000900', 'hex');
(buffer[12] >> 0) & ((1 << 4) - 1); // 9
(buffer[12] >> 4) & ((1 << 4) - 1); // 0
Migrated from https://github.com/joyent/node/pull/25595#issuecomment-128469192 per comment.
@mwillbanks Hi there, thanks for the contribution!
Are you able to put this into an npm module? It looks like a good candidate for that, since it's something that is able to be done without any c++ pain. :)