Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Node.Js Buffers to Binary

I am sending and receiving packets with the help of Node.JS Buffers but I am not sure how to convert these buffers into a binary representation. I tried this but it did not work

let buff = Buffer.alloc(10);
buff[0] = 10;
buff[1] = 16;
buff[2] = 20;
buff[3] = 32;
buff[4] = 9;

console.log(buff);
console.log(buff.toString('binary'));
like image 545
Dr.Dough Avatar asked Aug 05 '26 01:08

Dr.Dough


2 Answers

Acording to the documentation 'binary' is an alias for 'latin1'

If you want a binary representation the easiest way to get a string representation of the buffer with only 1 and 0 is to convert the buffer to hexadecimal his representation, then parse this representation into a BigInt, get the base 2 of the BigInt, and finally pad the string with non significant zeros

function buf2bin (buffer) {
  return BigInt('0x' + buffer.toString('hex')).toString(2).padStart(buffer.length * 8, '0')
}
like image 188
aret Avatar answered Aug 07 '26 14:08

aret


Simple reduce to string with padStart combination.

const buff = Buffer.alloc(10);
buff[0] = 10;
buff[1] = 16;
buff[2] = 20;
buff[3] = 32;
buff[4] = 9;

const paddedBinString = buff.reduce(
    (acc, byte) => (acc += byte.toString(2).padStart(8, "0")),
    ""
);

console.log(paddedBinString);
// 00001010 00010000 00010100 00100000 00001001 00000000 00000000 00000000 00000000 00000000
like image 35
Filip Seman Avatar answered Aug 07 '26 14:08

Filip Seman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!