Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert text to binary code in JavaScript?

Text to Binary Code

I want JavaScript to translate text in a textarea into binary code.

For example, if a user types in "TEST" into the textarea, the value "01010100 01000101 01010011 01010100" should be returned.

I would like to avoid using a switch statement to assign each character a binary code value (e.g. case "T": return "01010100) or any other similar technique.

Here's a JSFiddle to show what I mean. Is this possible in native JavaScript?

like image 329
Shrey Gupta Avatar asked Jan 20 '13 23:01

Shrey Gupta


People also ask

Does JavaScript use binary code?

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.

What is binary data in JavaScript?

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.

Can binary be converted to text?

How to use Binary to Text converter? Paste binary byte codes in input text box. Select character encoding type. Press the Convert button.


2 Answers

What you should do is convert every char using charCodeAt function to get the Ascii Code in decimal. Then you can convert it to Binary value using toString(2):

HTML:

<input id="ti1" value ="TEST"/> <input id="ti2"/> <button onClick="convert();">Convert!</button> 

JS:

function convert() {   var output = document.getElementById("ti2");   var input = document.getElementById("ti1").value;   output.value = "";   for (var i = 0; i < input.length; i++) {       output.value += input[i].charCodeAt(0).toString(2) + " ";   } } 

And here's a fiddle: http://jsfiddle.net/fA24Y/1/

like image 186
Majid Laissi Avatar answered Sep 25 '22 13:09

Majid Laissi


This might be the simplest you can get:

function text2Binary(string) {     return string.split('').map(function (char) {         return char.charCodeAt(0).toString(2);     }).join(' '); } 
like image 23
gnclmorais Avatar answered Sep 24 '22 13:09

gnclmorais