Friends how can I write a bit into Node js Buffer, I can write Byte, integers etc but do not know how to write bits. is it possible? if yes then how? I should write a bollean in buffer 1 or 0 and read it in API using readBit() thats why I need write a bit in the buffer.
Asked
Active
Viewed 3,825 times
1 Answers
8
You can't access a single bit directly, but can simply do some bit magic in JS.
This will enable you to read and write single bits to a Node Buffer (a Uint8Array).
var buffer = new Uint8Array(1);
function readBit(buffer, i, bit){
return (buffer[i] >> bit) % 2;
}
function setBit(buffer, i, bit, value){
if(value == 0){
buffer[i] &= ~(1 << bit);
}else{
buffer[i] |= (1 << bit);
}
}
// write bit 0 of buffer[0]
setBit(buffer, 0, 0, 1)
// write bit 1 of buffer[0]
setBit(buffer, 0, 1, 1)
setBit(buffer, 0, 1, 0)
// write bit 2 of buffer[0]
setBit(buffer, 0, 2, 0)
// write bit 3 of buffer[0]
setBit(buffer, 0, 3, 0)
setBit(buffer, 0, 3, 1)
// read back the bits
console.log(
readBit(buffer, 0, 0),
readBit(buffer, 0, 1),
readBit(buffer, 0, 2),
readBit(buffer, 0, 3)
);

Bellian
- 2,009
- 14
- 20
-
I understood the point but one more question, how can I apply this to the Node js Buffer ? For example let buffer = Buffer.alloc(10); buffer.writeUInt32BE(0); buffer.write( bit here ); This was my question :) – Rado Harutyunyan May 07 '18 at 14:07
-
Hi, a Node Buffer IS a Uint8Array with a few extra methods: https://nodejs.org/api/buffer.html#buffer_buffers_and_typedarray You can also create a plain Uint8Array from a buffer like so: `new Uint8Array(a.buffer, a.byteOffset, a.byteLength);` therefore you can simply use the code on a node buffer. the Uint8Array was used for this demo. – Bellian May 08 '18 at 05:06
-
The code is above. Just replace `new Uint8Array(1);` by `Buffer.alloc(10)`. there is no method for accessing bits directly you need to use methods like `setBit` or extend the prototype of Buffer with something like this: `Buffer.prototype.writeBit = function(i, bit, value){setBit(this, i, bit, value)}` – Bellian May 09 '18 at 10:19