如何在 JavaScript 中将文本转换为二进制代码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14430633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:43:41  来源:igfitidea点击:

How to convert text to binary code in JavaScript?

javascriptstringbinary

提问by Shrey Gupta

Text to Binary Code

文本到二进制代码

I want JavaScript to translate text in a textarea into binary code.

我希望 JavaScript 将 textarea 中的文本转换为二进制代码。

For example, if a user types in "TEST" into the textarea, the value "01010100 01000101 01010011 01010100" should be returned.

例如,如果用户在TESTtextarea 中键入“ ”,01010100 01000101 01010011 01010100则应返回值“ ”。

I would like to avoid using a switch statement to assign each character a binary code value (e.g. case "T": return "01010100) or any other similar technique.

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

Here's a JSFiddleto show what I mean. Is this possible in native JavaScript?

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

回答by Majid Laissi

What you should do is convert every char using charCodeAtfunction to get the Ascii Code in decimal. Then you can convert it to Binary value using toString(2):

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

HTML:

HTML:

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

JS:

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) + " ";
  }
}

And here's a fiddle: http://jsfiddle.net/fA24Y/1/

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

回答by gnclmorais

This might be the simplest you can get:

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

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

回答by alejandro

  1. traverse the string
  2. convert every character to their char code
  3. convert the char code to binary
  4. push it into an array and add the left 0s
  5. return a string separated by space
  1. 遍历字符串
  2. 将每个字符转换为其字符代码
  3. 将字符代码转换为二进制
  4. 将它推入一个数组并添加左边的 0
  5. 返回一个由空格分隔的字符串

Code:

代码:

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"

Another way

其它的办法

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(' ')
  );
}

回答by eyecatchUp

Here's a pretty generic, native implementation, that I wrote some time ago,

这是我前段时间写的一个非常通用的本地实现,

// ABC - a generic, native JS (A)scii(B)inary(C)onverter.
// (c) 2013 Stephan Schmitz <[email protected]>
// 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
  }
};

and to be used as follows:

并按如下方式使用:

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

Source is on Github (gist): https://gist.github.com/eyecatchup/6742657

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

Hope it helps. Feel free to use for whatever you want (well, at least for whatever MIT permits).

希望能帮助到你。随意使用你想要的任何东西(好吧,至少对于 MIT 允许的任何东西)

回答by Nevir

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

回答by jAndy

Just a hint into the right direction

只是一个指向正确方向的提示

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

回答by Hyper

8-bit characters with leading 0

前导 0 的 8 位字符

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

If you need 6 or 7 bit, just change .slice(-8)

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

回答by Beejor

The other answers will work for most cases. But it's worth noting that charCodeAt()and related don't work with UTF-8 strings (that is, they throw errors if there are any characters outside the standard ASCII range). Here's a workaround.

其他答案适用于大多数情况。但值得注意的是,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 );
};

The escape/unescape()functions are deprecated. If you need polyfills for them, you can check out the more comprehensive UTF-8 encoding example found here: http://jsfiddle.net/47zwb41o

escape/unescape()不推荐使用这些功能。如果您需要它们的 polyfill,您可以查看更全面的 UTF-8 编码示例:http: //jsfiddle.net/47zwb41o

回答by Martian2049

this seems to be the simplified version

这似乎是简化版

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

回答by Yarik

Thank you Majid Laissifor your answer

感谢Majid Laissi回答

I made 2 functions out from your code:

我从您的代码中创建了 2 个函数:

the goal was to implement convertation of string to VARBINARY, BINARY and back

目标是实现字符串到 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;
};

and backward convertation:

和向后转换:

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;
};

and here is a working example: https://jsbin.com/futalidenu/edit?js,console

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