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:
function convertBinary() { var output = document.getElementById("outputBinary"); var input = document.getElementById("inputBinary").value; output.value = ""; for (i = 0; i < input.length; i++) { var e = input[i].charCodeAt(0); var s = ""; do { var a = e % 2; e = (e - a) / 2; s = a + s; } while (e != 0); while (s.length < 8) { s = "0" + s; } output.value += s; } }
<div class="container"> <span class="main">Binary Converter</span><br> <textarea autofocus class="inputBinary" id="inputBinary" onKeyUp="convertBinary()"></textarea> <textarea class="outputBinary" id="outputBinary" readonly></textarea> <div class="about">Made by <strong>Omar</strong></div> </div>
Advertisement
Answer
Use toString(2)
to convert to a binary string. For example:
var input = document.getElementById("inputDecimal").value; document.getElementById("outputBinary").value = parseInt(input).toString(2);
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:
function BinToText() { var input = document.getElementById("inputBinary").value; document.getElementById("outputText").value = parseInt(input,2).toString(10); } ... <textarea autofocus class="inputBinary" id="inputBinary" onKeyUp="BinToText()"></textarea> <textarea class="outputBinary" id="outputText" readonly></textarea>
If you put 0100
in inputBinary
, you should get 4
in outputText
(not tested).