admin管理员组文章数量:1395885
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'));
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'));
Share
Improve this question
asked Mar 1, 2021 at 0:48
Dr.DoughDr.Dough
1651 gold badge2 silver badges6 bronze badges
5
- You built a buffer. That IS a binary representation already. So, what are you actually trying to acplish? What do you hope to do with it? – jfriend00 Commented Mar 1, 2021 at 3:30
- Just print the contents of the buffer into binary like separated with 8 bits. E.g) 10011001 00110010 – Dr.Dough Commented Mar 1, 2021 at 3:42
- 1 So, you want a binary string representation of each byte in the buffer? – jfriend00 Commented Mar 1, 2021 at 4:00
- Yes thats exactly what I want – Dr.Dough Commented Mar 1, 2021 at 4:43
- OK, my answer is below that does that. – jfriend00 Commented Mar 1, 2021 at 4:43
3 Answers
Reset to default 4Acording 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')
}
Simple reduce
to string with padStart
bination.
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
Here's how I do it:
const hexChar2bin = c =>
({
0: '0000',
1: '0001',
2: '0010',
3: '0011',
4: '0100',
5: '0101',
6: '0110',
7: '0111',
8: '1000',
9: '1001',
a: '1010',
b: '1011',
c: '1100',
d: '1101',
e: '1110',
f: '1111',
}[c]);
export default function buf2bin(buf) {
return buf.toString('hex').split('').map(hexChar2bin).join('');
}
console.log(buf2bin(Buffer.from(' '))); // 00100000 (space character is decimal 32)
本文标签: JavaScript NodeJs Buffers to BinaryStack Overflow
版权声明:本文标题:JavaScript Node.Js Buffers to Binary - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744089260a2589116.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论