0

How to convert a string to a byte in javascript and vice-versa?

Sample:

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

backtoBin(b); //10101010

Thank you.

zrzka
  • 20,249
  • 5
  • 47
  • 73
kaf
  • 41
  • 7
  • possible duplicate of [Converting byte array to string in javascript](http://stackoverflow.com/questions/3195865/converting-byte-array-to-string-in-javascript) – Artjom B. Jul 05 '15 at 01:04

3 Answers3

3

binary to integer

integer = parseInt(binary,2);

integer to binary

binary = integer.toString(2);
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
1

Using toString(2) you can convert a number to its binary value, to revert it you can use parseInt(binaryValue, 2). You could do it this way:

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

You can use parseInt(a, 2) with radix of 2 to convert the string to a value

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

And use Number(b).toString(2) to convert the integer to string

b = 170;
a = Number(b).toString(2); // results a = "10101010";
Ed Ballot
  • 3,405
  • 1
  • 17
  • 24