-1

I have something similar to the following code:

const fs = require('fs');

const imageBuffer = fs.readFileSync('path/to/image.jpg');

const binary = imageBuffer.toString('binary');

console.log(binary)

Which gives something like:

b'#F���S���g�p�Kj"�tJnv�^��'

I want to see the raw zeros and ones from the imageBuffer. How do I view this and why doesn't imageBuffer.toString('binary') work?

Jack
  • 397
  • 4
  • 13

1 Answers1

1

As the Node.js documentation states:

[The toString() function] decodes buf to a string according to the specified character encoding in encoding.

What this means is that toString() decodes the buffer to a string using a specific encoding. Node.js supports multiple encodings, one of which is binary, but as the documentation also states:

'binary': Alias for [the] 'latin1' [encoding]... The name of ['binary'] encoding can be very misleading, as all of the encodings listed here convert between strings and binary data. For converting between strings and Buffers, typically 'utf8' is the right choice.

So the 'binary' encoding option does not mean that the string will give you zeros and ones. It means that it will give you imageBuffer in latin1 encoding.

To view the actual zeros and ones, you could do something like this:

const fs = require('fs');

const imageBuffer = fs.readFileSync('path/to/image.jpg');

let binaryString = '';
for (let i = 0; i < imageBuffer.length; i++) {
  const byte = imageBuffer.readUInt8(i);
  binaryString += byte.toString(2).padStart(8, '0');
}

console.log(binaryString)

Which should give you something like:

01000101 01100001 01110011 01110100 00100000 01101111 01100110
00100000 01000101 01100100 01100101 01101110 00100000 01101001
01110011 00100000 01100001 00100000 01101110 01101111 01110110 ...

If this is still confusing to you, I'd recommend you read more about buffers, encoding, and decoding.

Jack
  • 397
  • 4
  • 13