js如何将0和1组成的字符串转为字节

js how to convert a string of 0 and 1 to a byte

如何在 javascript 中将字符串转换为字节,反之亦然?

示例:

a = "10101010";
b = toByte(a); //char(170)

backtoBin(b); //10101010

谢谢。

使用toString(2) you can convert a number to its binary value, to revert it you can use parseInt(binaryValue, 2)。你可以这样做:

function toByte(str){
  return parseInt(str, 2);
}
function backtoBin(num){
  return num.toString(2);
}

var a = "10101010";
var b = toByte(a); //170
var c = backtoBin(b); //10101010

console.log(b, c)
<script src="http://www.wzvang.com/snippet/ignore_this_file.js"></script>

二进制转整数

integer = parseInt(binary,2);

整数转二进制

binary = integer.toString(2);

您可以使用基数为 2 的 parseInt(a, 2) 将字符串转换为值

a = "1010101010";
b = parseInt(a, 2); // results in b = 170

并使用Number(b).toString(2)将整数转换为字符串

b = 170;
a = Number(b).toString(2); // results a = "10101010";