I am aware that a similar question has already been asked before (see How to read a single bit buffer in node), but it seems none of the answers are helful. The first comment that has been accepted, stating to use buf.readUIntLE()
, is not working since 2 arguments are expected, but 0 was provided.
Thus, I am currently trying to read a single bit (the 17th one) from a Buffer, but I can't find a way to easily read it. I have been using buffer.readUInt16BE(0)
to read the 2 first bytes of the Buffer and so far it works fine, but I need to assign the 17th bit to a variable.
Note: My Buffer data is Big-Endian and I am coding in TypeScript.
I thought about doing something like:
const myVar: number = parseInt(buffer.readUIntBE(2, 1).toString().slice(0,1));
in order to read, then stringify the 3th byte, then getting the first caracter and convert it into a number, but I find it very clunky.
Is there a simple way to achieve this ?
CodePudding user response:
A buffer is also a Uint8Array
typed array, you can simply access its bytes by index. (If you prefer to do it with a method call, the equivalent would be readUint8
). Then simply access the respective bit in that byte:
const position = 17;
const bitIndex = position & 7; // in byte
const byteIndex = position >> 3; // in buffer
const bit = (buffer[byteIndex] >> bitIndex) & 1
(Regarding the numbers: there are 8
= 2³
bits in a byte, and 7
is (1<<3)-1
or 0b111
)