1

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.

1 Answer 1

9

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)
);

Sign up to request clarification or add additional context in comments.

3 Comments

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 :)
Hi, a Node Buffer IS a Uint8Array with a few extra methods: 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.
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)}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.