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="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></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.
Example 2: Convert Decimal to Binary Using toString() The parseInt() method is used to convert a string value to an integer. The JavaScript built-in method toString([radix]) returns a string value in a specified radix (base). Here, toString(2) converts the decimal number to binary number.
JavaScript Uses 32 bits Bitwise Operands JavaScript stores numbers as 64 bits floating point numbers, but all bitwise operations are performed on 32 bits binary numbers. Before a bitwise operation is performed, JavaScript converts numbers to 32 bits signed integers.
Binary data in JavaScript is implemented in a non-standard way, compared to other languages. But when we sort things out, everything becomes fairly simple. The basic binary object is ArrayBuffer – a reference to a fixed-length contiguous memory area.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With