Skip to content
This repository has been 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

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

wants to merge 1 commit into from

Conversation

mwillbanks
Copy link

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 nodejs/node-v0.x-archive#25595 (comment) per comment.

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.
@Fishrock123
Copy link
Contributor

@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. :)

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants