为什么Node.js不为二进制值输出0和1?

时间:2019-03-12 11:45:13

标签: javascript node.js binary

我正在尝试学习二进制文件并为我想到的编程思想构建一个库,以更好地理解Javascript和基本编程技术。将字符串值转换为二进制格式时,我注意到由于某种原因,Node无法接收该字符串的0和1值。我将学习如何将字符串转换为二进制形式,然后搜索它们以找到要从所述字符串中删除的某些值。

关于某个字符串如何以0和1输出二进制表示的任何想法?

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

1 个答案:

答案 0 :(得分:2)

一个想法是将每个字符转换为相应的ASCII代码,然后使用toString(2)以二进制表示形式转换该代码,并在结尾处将每个二进制字符串加零以使其变为8位

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))