Ad

Why Does Node.js Not Output 0's And 1's For A Binary Value?

- 1 answer

I am trying to learn binary and build a library for a programming idea I came up with, to better my understanding of Javascript and fundamental programming techniques. When converting a string value to its binary form, I noticed I can not receive the 0's and 1's value for that string for some reason by Node. I was going to learn how to convert strings to binary form, then search them to find certain values to remove from said string.

Any idea on how to output the binary representation in 0's and 1's for a certain string?

let example_one = 'A';
let buf = Buffer.from(example_one, 'binary');
for (let i = 0; i < buf.length; i++) {
    console.log(`Example 1: ${buf[i]}`)
}
// Example 1:
// A
let example_two = Buffer.alloc(10);
console.log(example_two);
// Example 2: (Some 0's finally appear, do not understand it though
// <Buffer 00 00 00 00 00 00 00 00 00 00>
let example_three = Buffer.from("B", "binary");
console.log(`Example 3: ${example_three}`);
// Example 3: (No zero's)
// B
let example_four = 'Test'.toString('binary');
// Example 4:
// Test
Ad

Answer

An idea would be to convert each character to its corresponding ASCII code, then convert that code in its binary representation using toString(2) and in the end pad each binary string with zeroes to make it 8 bit.

var data = 'test'

function to8bitBinary(s){

  // put each char into an array using spread operator of ES6
  let arrayOfChars = [...s]

  return arrayOfChars
    .map(v => v.charCodeAt()) // convert chars into ASCII codes
    .map(v => v.toString(2))  // convert ASCII codes into binary strings
    .map(v => '0'.repeat(8 - v.length) + v) // pad zeroes to make 8bit strings
}

console.log(to8bitBinary(data))

Ad
source: stackoverflow.com
Ad