reselbob
reselbob

Reputation: 415

How do I convert a byte array in NodeJS to binary output

I have a byte array I've created in NodeJS that displays like so:

<Buffer 0a 0d 42 69 67 20 42 6f 62 20 53 6d 69 74 68 10 1e 1a 12 62 69 67 62 6f 62 40 65 78 61 6d 70 6c 65 2e 63 6f 6d>.

I want to write some code in NodeJS that will display the byte array as binary, like so:

1010000011010100001001101001011001110010000001000010011011110110001000100000010100110110110101101001011101000110100000010000000111100001101000010010011000100110100101100111011000100110111101100010010000000110010101111000011000010110110101110000011011000110010100101110011000110110111101101101

I've been looking around for a package on NPM, but have come up short.

Thanks in advance for any help.

Upvotes: 1

Views: 1420

Answers (1)

Yann LM
Yann LM

Reputation: 71

If you want to get the binary version of your buffer's data, here is an example :

const buffer = Buffer.from([0x0a, 0x0d, 0x42, 0x69, 0x67, 0x20, 0x42, 0x6f, 0x62, 0x20, 0x53, 0x6d, 0x69, 0x74, 0x68, 0x10, 0x1e, 0x1a, 0x12, 0x62, 0x69, 0x67, 0x62, 0x6f, 0x62, 0x40, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x63, 0x6f, 0x6d]);
const paddedBin = BigInt('0x' + buffer.toString('hex')).toString(2).padStart(buffer.length * 8, '0')


console.log(paddedBin);

// output => 00001010000011010100001001101001011001110010000001000010011011110110001000100000010100110110110101101001011101000110100000010000000111100001101000010010011000100110100101100111011000100110111101100010010000000110010101111000011000010110110101110000011011000110010100101110011000110110111101101101

Upvotes: 3

Related Questions