How can I convert Binary code to text using JavaScript? I have already made it convert text to binary but is there a way of doing it the other way around?
Here is my code:
JavaScript
x
18
18
1
function convertBinary() {
2
var output = document.getElementById("outputBinary");
3
var input = document.getElementById("inputBinary").value;
4
output.value = "";
5
for (i = 0; i < input.length; i++) {
6
var e = input[i].charCodeAt(0);
7
var s = "";
8
do {
9
var a = e % 2;
10
e = (e - a) / 2;
11
s = a + s;
12
} while (e != 0);
13
while (s.length < 8) {
14
s = "0" + s;
15
}
16
output.value += s;
17
}
18
}
JavaScript
1
6
1
<div class="container">
2
<span class="main">Binary Converter</span><br>
3
<textarea autofocus class="inputBinary" id="inputBinary" onKeyUp="convertBinary()"></textarea>
4
<textarea class="outputBinary" id="outputBinary" readonly></textarea>
5
<div class="about">Made by <strong>Omar</strong></div>
6
</div>
Advertisement
Answer
Use toString(2)
to convert to a binary string. For example:
JavaScript
1
3
1
var input = document.getElementById("inputDecimal").value;
2
document.getElementById("outputBinary").value = parseInt(input).toString(2);
3
or parseInt(input,10)
if you know the input should be decimal. Otherwise input of “0x42” will be parsed as hex rather than decimal.
EDIT: Just re-read the question. To go from binary to text, use parseInt(input,2).toString(10).
Everything above is for numbers only. E.g., 4
<-> 0100
. If you want 4
<-> decimal 52 (its ASCII value), use String.fromCharCode()
(see this answer).
EDIT 2: per request for where everything fits, try this:
JavaScript
1
8
1
function BinToText() {
2
var input = document.getElementById("inputBinary").value;
3
document.getElementById("outputText").value = parseInt(input,2).toString(10);
4
}
5
6
<textarea autofocus class="inputBinary" id="inputBinary" onKeyUp="BinToText()"></textarea>
7
<textarea class="outputBinary" id="outputText" readonly></textarea>
8
If you put 0100
in inputBinary
, you should get 4
in outputText
(not tested).