Skip to content
Advertisement

Converting Binary to text using JavaScript

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
JavaScript

Advertisement

Answer

Use toString(2) to convert to a binary string. For example:

JavaScript

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

If you put 0100 in inputBinary, you should get 4 in outputText (not tested).

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement