【问题标题】:How to convert text to binary code in JavaScript?如何在 JavaScript 中将文本转换为二进制代码?
【发布时间】:2013-01-04 00:50:36
【问题描述】:

文本转二进制代码

我希望 JavaScript 将 textarea 中的文本翻译成二进制代码。

例如,如果用户在文本区域中输入“TEST”,则应返回值“01010100 01000101 01010011 01010100”。

我想避免使用 switch 语句为每个字符分配二进制代码值(例如case "T": return "01010100)或任何其他类似技术。

这里有一个JSFiddle 来说明我的意思。这在原生 JavaScript 中可行吗?

【问题讨论】:

  • 通过谷歌找到这个。我想这就是你要找的。 roubaixinteractive.com/PlayGround/Binary_Conversion/…
  • 你有 charCodeAt 方法用于 js 中的字符串
  • 人们应该知道,字符串在 JavaScript 中以 UTF-16 格式存储。因此,您将拥有 UTF-16 二进制表示。如果您想要其他内容,例如 UTF-8,则必须在编码为二进制之前手动将字符码转换为 UTF-8(例如 here)。

标签: javascript string binary


【解决方案1】:

您应该做的是使用charCodeAt 函数转换每个字符以获得十进制的Ascii 代码。然后您可以使用toString(2) 将其转换为二进制值:

HTML:

<input id="ti1" value ="TEST"/>
<input id="ti2"/>
<button onClick="convert();">Convert!</button>

JS:

function convert() {
  var output = document.getElementById("ti2");
  var input = document.getElementById("ti1").value;
  output.value = "";
  for (var i = 0; i < input.length; i++) {
      output.value += input[i].charCodeAt(0).toString(2) + " ";
  }
}

这是一个小提琴:http://jsfiddle.net/fA24Y/1/

【讨论】:

  • 左垫的替代方式:var a = 'a'.charCodeAt(0).toString(2); /* a == "1100001" */ a = new Array(9 - a.length).join('0') + a; /* a == "01100001" */.
  • 问题:是否有其他方法可以做到这一点,例如使用此文本制作一个 blob,然后使用 filereader 将其输出为二进制数据......但它似乎只是为我输出文本.
  • 未来读者注意事项:请注意,字符集不限于 8 位。试试charToBin("?")
  • 为什么不改为“input.charCodeAt(i)”?
  • 这有前导零的问题。 output.value += (0b100000000 + input[i].charCodeAt(0)).toString(2).substring(1) + " "; 修复它
【解决方案2】:

这可能是你能得到的最简单的:

function text2Binary(string) {
    return string.split('').map(function (char) {
        return char.charCodeAt(0).toString(2);
    }).join(' ');
}

【讨论】:

    【解决方案3】:
    1. 遍历字符串
    2. 将每个字符转换为它们的字符代码
    3. 将字符代码转换为二进制代码
    4. 将其压入数组并添加左边的 0
    5. 返回一个以空格分隔的字符串

    代码:

    function textToBin(text) {
      var length = text.length,
          output = [];
      for (var i = 0;i < length; i++) {
        var bin = text[i].charCodeAt().toString(2);
        output.push(Array(8-bin.length+1).join("0") + bin);
      } 
      return output.join(" ");
    }
    textToBin("!a") => "00100001 01100001"
    

    另一种方式

    function textToBin(text) {
      return (
        Array
          .from(text)
          .reduce((acc, char) => acc.concat(char.charCodeAt().toString(2)), [])
          .map(bin => '0'.repeat(8 - bin.length) + bin )
          .join(' ')
      );
    }
    

    【讨论】:

    • 您可以省略 9-bin.length+1 中的 +1,方法是将 8 设置为 9 像这样 function textToBin(text) { var length = text.length, output = []; for (var i = 0;i &lt; length; i++) { var bin = text[i].charCodeAt().toString(2); output.push(Array(9-bin.length).join("0") + bin); } return output.join(" "); }
    • 更简单的是output.push(('0000000' + bin).slice(-8))。 ;-) 但是有些字符,比如 endash,超过 8 位:charCode 8212 -> 10000000010100。
    【解决方案4】:

    这是一个非常通用的原生实现,I wrote some time ago

    // ABC - a generic, native JS (A)scii(B)inary(C)onverter.
    // (c) 2013 Stephan Schmitz <eyecatchup@gmail.com>
    // License: MIT, http://eyecatchup.mit-license.org
    // URL: https://gist.github.com/eyecatchup/6742657
    var ABC = {
      toAscii: function(bin) {
        return bin.replace(/\s*[01]{8}\s*/g, function(bin) {
          return String.fromCharCode(parseInt(bin, 2))
        })
      },
      toBinary: function(str, spaceSeparatedOctets) {
        return str.replace(/[\s\S]/g, function(str) {
          str = ABC.zeroPad(str.charCodeAt().toString(2));
          return !1 == spaceSeparatedOctets ? str : str + " "
        })
      },
      zeroPad: function(num) {
        return "00000000".slice(String(num).length) + num
      }
    };
    

    并按如下方式使用:

    var binary1      = "01100110011001010110010101101100011010010110111001100111001000000110110001110101011000110110101101111001",
        binary2      = "01100110 01100101 01100101 01101100 01101001 01101110 01100111 00100000 01101100 01110101 01100011 01101011 01111001",
        binary1Ascii = ABC.toAscii(binary1),
        binary2Ascii = ABC.toAscii(binary2);
    
    console.log("Binary 1:                   " + binary1);
    console.log("Binary 1 to ASCII:          " + binary1Ascii);
    console.log("Binary 2:                   " + binary2);
    console.log("Binary 2 to ASCII:          " + binary2Ascii);
    console.log("Ascii to Binary:            " + ABC.toBinary(binary1Ascii));     // default: space-separated octets
    console.log("Ascii to Binary /wo spaces: " + ABC.toBinary(binary1Ascii, 0));  // 2nd parameter false to not space-separate octets
    

    来源在 Github(要点):https://gist.github.com/eyecatchup/6742657

    希望对您有所帮助。随意使用任何你想要的东西(嗯,至少对于 MIT 允许的任何东西)

    【讨论】:

      【解决方案5】:
      var PADDING = "00000000"
      
      var string = "TEST"
      var resultArray = []
      
      for (var i = 0; i < string.length; i++) {
        var compact = string.charCodeAt(i).toString(2)
        var padded  = compact.substring(0, PADDING.length - compact.length) + compact
      
        resultArray.push(padded)
      }
      
      console.log(resultArray.join(" "))
      

      【讨论】:

      【解决方案6】:

      其他答案适用于大多数情况。但值得注意的是,charCodeAt() 和相关内容不适用于 UTF-8 字符串(也就是说,如果有任何超出标准 ASCII 范围的字符,它们会抛出错误)。这是一种解决方法。

      // UTF-8 to binary
      var utf8ToBin = function( s ){
          s = unescape( encodeURIComponent( s ) );
          var chr, i = 0, l = s.length, out = '';
          for( ; i < l; i ++ ){
              chr = s.charCodeAt( i ).toString( 2 );
              while( chr.length % 8 != 0 ){ chr = '0' + chr; }
              out += chr;
          }
          return out;
      };
      
      // Binary to UTF-8
      var binToUtf8 = function( s ){
          var i = 0, l = s.length, chr, out = '';
          for( ; i < l; i += 8 ){
              chr = parseInt( s.substr( i, 8 ), 2 ).toString( 16 );
              out += '%' + ( ( chr.length % 2 == 0 ) ? chr : '0' + chr );
          }
          return decodeURIComponent( out );
      };
      

      escape/unescape() 函数已弃用。如果你需要 polyfill,你可以在这里查看更全面的 UTF-8 编码示例:http://jsfiddle.net/47zwb41o

      【讨论】:

        【解决方案7】:

        前导 0 的 8 位字符

        'sometext'
                .split('')
                .map((char) => '00'.concat(char.charCodeAt(0).toString(2)).slice(-8))
                .join(' ');
        

        如果您需要 6 或 7 位,只需更改 .slice(-8)

        【讨论】:

          【解决方案8】:

          感谢 Majid Laissianswer

          我用你的代码做了两个函数:

          目标是实现字符串到 VARBINARY、BINARY 和返回的转换

          const stringToBinary = function(string, maxBytes) {
            //for BINARY maxBytes = 255
            //for VARBINARY maxBytes = 65535
            let binaryOutput = '';
            if (string.length > maxBytes) {
              string = string.substring(0, maxBytes);
            }
          
            for (var i = 0; i < string.length; i++) {
              binaryOutput += string[i].charCodeAt(0).toString(2) + ' ';
            }
          
            return binaryOutput;
          };
          

          和反向转换:

          const binaryToString = function(binary) {
            const arrayOfBytes = binary.split(' ');
          
            let stringOutput = '';
          
            for (let i = 0; i < arrayOfBytes.length; i++) {
              stringOutput += String.fromCharCode(parseInt(arrayOfBytes[i], 2));
            }
          
            return stringOutput;
          };
          

          这是一个工作示例:https://jsbin.com/futalidenu/edit?js,console

          【讨论】:

            【解决方案9】:

            只是对正确方向的提示

            var foo = "TEST",
                res = [ ];
            
            foo.split('').forEach(function( letter ) {
                var bin     = letter.charCodeAt( 0 ).toString( 2 ),
                    padding = 8 - bin.length;
            
                res.push( new Array( padding+1 ).join( '0' ) + bin );
            });
            
            console.log( res );
            

            【讨论】:

              【解决方案10】:

              这似乎是简化版

              Array.from('abc').map((each)=>each.charCodeAt(0).toString(2)).join(" ")
              

              【讨论】:

                【解决方案11】:

                如果您在 node 或支持 BigInt 的浏览器中工作,此版本通过节省昂贵的字符串构造来降低成本:

                const zero = 0n
                const shift = 8n
                
                function asciiToBinary (str) {
                  const len = str.length
                  let n = zero
                  for (let i = 0; i < len; i++) {
                    n = (n << shift) + BigInt(str.charCodeAt(i))
                  }
                  return n.toString(2).padStart(len * 8, 0)
                }
                

                它的速度大约是此处提到的其他解决方案的两倍,包括这个简单的 es6+ 实现:

                const toBinary = s => [...s]
                  .map(x => x
                    .codePointAt()
                    .toString(2)
                    .padStart(8,0)
                  )
                  .join('')
                

                如果你需要处理 unicode 字符,这里是这个人:

                const zero = 0n
                const shift = 8n
                const bigShift = 16n
                const byte = 255n
                
                function unicodeToBinary (str) {
                  const len = str.length
                  let n = zero
                  for (let i = 0; i < len; i++) {
                    const bits = BigInt(str.codePointAt(i))
                    n = (n << (bits > byte ? bigShift : shift)) + bits
                  }
                  const bin = n.toString(2)
                  return bin.padStart(8 * Math.ceil(bin.length / 8), 0)
                }
                

                【讨论】:

                  【解决方案12】:

                  这是尽可能短的。它基于评分最高的答案,但已转换为 reduce 函数。

                  "TEST".split("").reduce(function (a, b) { return a + b.charCodeAt(0).toString(2)}, "")
                  

                  【讨论】:

                    【解决方案13】:

                    const textToBinary = (string) => {
                        return string.split('').map((char) => 
                          char.charCodeAt().toString(2)).join(' ');
                    }
                    
                    console.log(textToBinary('hello world'))

                    【讨论】:

                    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
                    【解决方案14】:
                    var UTF8ToBin=function(f){for(var a,c=0,d=(f=unescape(encodeURIComponent(f))).length,b="";c<d;c++){for(a=f.charCodeAt(c).toString(2);a.length%8!=0;){a="0"+a}b+=a}return b},binToUTF8=function(f){for(var a,c=0,d=f.length,b="";c<d;c+=8){b+="%"+((a=parseInt(f.substr(c,8),2).toString(16)).length%2==0?a:"0"+a)}return decodeURIComponent(b)};
                    

                    这是一个小型的 JavaScript 代码,用于将 UTF8 转换为二进制,反之亦然。

                    【讨论】:

                      【解决方案15】:

                      这是基于 UTF-8 的文本二进制表示的解决方案。它利用 TextEncoder,将字符串编码为其 UTF-8 字节。

                      此解决方案以空格分隔字符。多字节字符的各个“字节位”由减号字符 (-) 分隔。

                      // inspired by https://stackoverflow.com/a/40031979/923560
                      function stringToUtf8BinaryRepresentation(inputString) {
                        const result = Array.from(inputString).map(
                          char => [... new TextEncoder().encode(char)].map(
                            x => x.toString(2).padStart(8, '0')
                          ).join('-')
                        ).join(' ');
                        return result;
                      }
                      
                      // ### example usage #########################
                      function print(inputString) {
                        console.log("--------------");
                        console.log(inputString);
                        console.log(stringToUtf8BinaryRepresentation(inputString));
                      }
                      
                      // compare with https://en.wikipedia.org/wiki/UTF-8#Encoding
                      // compare with https://en.wikipedia.org/wiki/UTF-8#Codepage_layout
                      // compare with UTF-16, which JavaScript uses for strings: https://en.wikipedia.org/wiki/UTF-16#Examples
                      
                      print("TEST");
                      print("hello world");
                      print("$");
                      print("£");
                      print("€");
                      print("한");
                      print("?");
                      print("παράδειγμα");
                      
                      print("?");
                      print("?‍?‍?‍?");
                      print("??‍?‍??");
                      print("??");

                      【讨论】:

                        猜你喜欢
                        • 1970-01-01
                        • 2020-03-22
                        • 2014-02-16
                        • 2014-02-17
                        • 1970-01-01
                        • 1970-01-01
                        • 2022-08-13
                        • 2021-05-01
                        相关资源
                        最近更新 更多