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...
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;
}
}
<script src=""></script>
<center>
<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>
</center>
Any help will be greatly appreciated.
Thanks, Omar.
23 Answers
I recently completed an exercise on this using a for loop. Hope it's useful:
function binaryAgent(str) {
var newBin = str.split(" ");
var binCode = [];
for (i = 0; i < newBin.length; i++) {
binCode.push(String.fromCharCode(parseInt(newBin[i], 2)));
}
return binCode.join("");
}
binaryAgent('01000001 01110010 01100101 01101110 00100111 01110100');
//translates to "Aren't"
EDIT: after learning more JavaScript, I was able to shortened the solution:
function binaryAgent(str) {
var binString = '';
str.split(' ').map(function(bin) {
binString += String.fromCharCode(parseInt(bin, 2));
});
return binString;
}
binaryAgent('01000001 01110010 01100101 01101110 00100111 01110100');
//translates to "Aren't"
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).
Similar to another answer if someone is still looking for this. the first split returns an list of strings, each of which represents a binary character.
Then we call map on each of these strings eg, "11001111" or whatever and return the fromCharCode on that element with parseInt nested. Then put .join() on the total returned value and it should work.
function binaryAgent3(str) {
return str.split(" ").map(function(elem) {
return String.fromCharCode(parseInt(elem, 2));
}).join("")
}
Original problem:
I ran into the same thing where I wanted to have Binary converted to text and this is what I came up with.
function binaryToWords(str) {
if(str.match(/[10]{8}/g)){
var wordFromBinary = str.match(/([10]{8}|\s+)/g).map(function(fromBinary){
return String.fromCharCode(parseInt(fromBinary, 2) );
}).join('');
return console.log(wordFromBinary);
}
}
binaryToWords('01000011 01101111 01100110 01100110 01100101 01100101 00100000 01101001 01110011 00100000 01100011 01101111 01101100 01100100 ');
Here is the code I wrote which converts binary to string. The only difference - it is shorter and relies on builtin JS functions.
function binarytoString(str) {
return str.split(/\s/).map(function (val){
return String.fromCharCode(parseInt(val, 2));
}).join("");
}
My solution for converting binary codes to text. Nothing extra. Most simple version, I think.
function binaryAgent(str) {
return str.split(" ").map(x => String.fromCharCode(parseInt(x, 2))).join("");
}
console.log(binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111"));
How about this?
function binaryAgent(str) {
var splitStr = str.split(" ");
var newVar = splitStr.map(function(val) {
return String.fromCharCode(parseInt(val,2).toString(10));
});
str = newVar.join("");
return str;
}
binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111"); // should return "Aren't bonfires fun!?"
This should work, and you don't need to give it "pretty" binary.
function binaryToString(binary) {
return binary.replace(/[01]{8}/g, function(v){
return String.fromCharCode(parseInt(v, 2));
});
}
if you are looking for 1 line solution.
function binary(str) {
return str.split(/\s/g).map((x) => x = String.fromCharCode(parseInt(x, 2))).join("");
}
//returns "one line"
binary("01101111 01101110 01100101 00100000 01101100 01101001 01101110 01100101");
If you are aware that only binary is being passed, you could use this function that has only 1 simple line:
function binaryAgent(str) {
return str.split(" ").map(input => String.fromCharCode(parseInt(input,2).toString(10))).join("");
}
// Calling the function
binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");
Shorter Code
function binaryAgent(str) {
let array = str.split(" ");
return array.map(code => String.fromCharCode(parseInt(code, 2))).join("");
}
console.log(binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111"));
// should return "Aren't bonfires fun!?"
This is also an operation you can delegation on the String prototype, although rarely recommended to update a global object type.
/** Returns a converted binary string to text */
String.prototype.binaryToText = function() {
return this
.match(/.{1,8}/g)
.join(' ')
.split(' ')
.reduce((a, c) => a += String.fromCharCode(parseInt(c, 2)), '');
}
const result = '01110101011100000010000001110110011011110111010001100101'.binaryToText();
console.log(result);
One line (Arrow) function:
let binToStr = (str) => str.split(' ').map((x) => String.fromCharCode(parseInt(x,2))).join('')
//Output: "Are fun!"
console.log(binToStr("01000001 01110010 01100101 00100000 01100110 01110101 01101110 00100001"));
My solution is a whole lot like map, only I used reduce. Break it up into an array, use reduce to convert the characters and add them to a new Array and join the new Array together.
function binaryAgent(str) {
var sentence = str.split(" ").reduce(function(x, y){
x.push(String.fromCharCode(parseInt(y, 2)));
return x;
}, []).join('');
return sentence;
}
Another similar answer if someone looking for this
function binaryAgent(str) {
var strArray = str.split(" ");
var text ="";
for(var i = 0 ; i<strArray.length ; i++){
var char = parseInt(strArray[i],2).toString(10);
char = String.fromCharCode(char);
text += char;
}
return text;
}
binaryAgent("01101101 01100101 01110110");
A problem that i found every providen solution was that if the binary string ain't "pretty printed" it won't convert it into a string:
function binaryAgent(str) {
var binString = '';
str.split(' ').map(function(bin) {
binString += String.fromCharCode(parseInt(bin, 2));
});
return binString;
}
// This displays "Aren't"
binaryAgent('01000001 01110010 01100101 01101110 00100111 01110100');
//But this not
binaryAgent('010000010111001001100101011011100010011101110100');
A quick solution is to remove all the spaces from the string (if there's any, otherwise the instruction to split doesn't work well) every 8 characters:
function binaryAgent(str) {
// Removes the spaces from the binary string
str = str.replace(/\s+/g, '');
// Pretty (correct) print binary (add a space every 8 characters)
str = str.match(/.{1,8}/g).join(" ");
var binString = '';
str.split(' ').map(function(bin) {
binString += String.fromCharCode(parseInt(bin, 2));
});
return binString;
}
// Both display "Aren't"
binaryAgent('01000001 01110010 01100101 01101110 00100111 01110100');
binaryAgent('010000010111001001100101011011100010011101110100');
For those who prefer .forEach() instead of loops, the following works as well:
function binaryToHuman(str) {
// split string into an array so we can loop through it
var newStr=str.split(" ");
// declare a new array to later push "translated" values into
var sArr=[];
// loop through binary array, translate and push translated values into the new array
newStr.forEach(function(item){
sArr.push(String.fromCharCode(parseInt(item,2)));
})
// join the array back into a string
return sArr.join("");
}
console.log(binaryToHuman("01001001 00100000 01101100 01101111 01110110 01100101 00100001"));
// returns:
// I love!
My solution just uses a regex to split bytes into an array, loops through each byte, converts binary to ascii and makes it into a string at end
function binaryAgent(str) {
//Splits into an array
var re = /\s/;
var newArr=str.split(re)
var answerArr =[];
//Decimal Conversion
for (let i=0; i<newArr.length; i++){
answerArr.push(String.fromCharCode(parseInt(newArr[i],2)));
}
return answerArr.join('');
}
binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");
Here's my solution with as much ES6 syntax as possible:
const binaryAgent = str => {
let code = str.split(" ")
let s = code.map((d) => parseInt(d,2))
let res = s.map((d) => String.fromCharCode(d))
return res.join("")
}
binaryAgent("01001001 00100000 01101100 01101111 01110110 01100101 00100000 01000110 01110010 01100101 01100101 01000011 01101111 01100100 01100101 01000011 01100001 01101101 01110000 00100001")
It should return I love FreeCodeCamp!
const whoTookTheCarKey = message =>
message.toString().split(',')
.map(message => String.fromCharCode(parseInt(message, 2)))
.join('')enter code here
One-liner solution with ES6 syntax, using split, map and join functions
function convertBinary(binary){
return binary.split(" ").map((x) => x = String.fromCharCode(parseInt(x, 2))).join("");
}
console.log(convertBinary("01001000 01100101 01101100 01101100 01101111 00100001"));
//This will print Hello!
- Separate the binary numbers into an array with the
splitmethod. - Use the
mapmethod to iterate over each binary number that is in the array and convert it to its corresponding letter with thefromCharCodemethod of the String object (You must first convert the binary number to decimal as follows:parseInt (bin, 2)for thefromCharCodemethod to work properly). - Add the letter returned by the
fromCharCodemethod to the variable that will contain the result.
function convertBinary(str) {
let result = "";
str.split(" ").map(bin => {
result += String.fromCharCode(parseInt(bin, 2))
})
return result;
}
This is a minor adjustment to JosephD's "One line (Arrow) function" answer...
When an arrow function has a single parameter, you can omit the parenthesis (). You can omit them in both the arrow function and the .map method like so:
let binToStr = str => str.split(' ').map(x => String.fromCharCode(parseInt(x,2))).join('');