代码之家  ›  专栏  ›  技术社区  ›  ABC

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

  •  0
  • ABC  · 技术社区  · 7 年前

    为了更好地理解Javascript和基本编程技术,我正在尝试学习二进制代码,并为我提出的一个编程思想构建一个库。在将字符串值转换为二进制形式时,我注意到由于某种原因,节点无法接收该字符串的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 回复  |  直到 7 年前
        1
  •  2
  •   Fredo Corleone    7 年前

    一个想法是将每个字符转换为相应的字符 ASCII 代码,然后使用 toString(2)

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