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.
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.
binary to integer
integer = parseInt(binary,2);
integer to binary
binary = integer.toString(2);
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>
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";