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):
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) + " ";
}
}
<input id="ti1" value ="TEST"/>
<input id="ti2"/>
<button onClick="convert();">Convert!</button>
Run code snippetEdit code snippet Hide Results Copy to answer Expand
And here's a fiddle: http://jsfiddle.net/fA24Y/1/
Answer from Majid Laissi on Stack OverflowWhat 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):
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) + " ";
}
}
<input id="ti1" value ="TEST"/>
<input id="ti2"/>
<button onClick="convert();">Convert!</button>
Run code snippetEdit code snippet Hide Results Copy to answer Expand
And here's a fiddle: http://jsfiddle.net/fA24Y/1/
This might be the simplest you can get:
function text2Binary(text) {
return text.split('').map(function (char) {
return char.charCodeAt(0).toString(2);
}).join(' ');
}
Update — using arrow functions:
function text2Binary(text) {
return text.split('').map((char) => char.charCodeAt(0).toString(2)).join(' ');
}
[AskJS] Shortest way to convert string to 8-bit binary?
javascript - Converting a string into binary and back - Stack Overflow
Binary string - JavaScript convert text to binary string - The freeCodeCamp Forum
Binary to String in JavaScript - Stack Overflow
String to 8-bit binary Codegolf
JavaScript is a verbose language, it can be hard to shorten certain things down.
For fun, lets try finding the shortest code (least bytes) that converts a string into 8-bit binary.
The infuriating part about this Codegolf, is that the solution with the least bytes is also the simplest piece of JavaScript.
So the question becomes, can we come up with a CodeGolf that beats a caveman ES6 for...of loop.
Code requirements:
-
You have to explicitly pass the string "Hello world!" in your code.
-
Executing the code, it has to return the binary string "010010000110010101101100011011000110111100100000011101110110111101110010011011000110010000100001".
All the quirks of JavaScript are allowed, as long as it can run in a browser.
Solutions we found:
s='';for(c of"Hello world!")s+=c.charCodeAt().toString(2).padStart(8,0)
71 bytes
s='';for(c of"Hello world!")s+=(c.charCodeAt()|256).toString(2).slice(1)
72 bytes
s='';for(c of"Hello world!")s+=`00${c.charCodeAt().toString(2)}`.slice(-8)
74 bytes
[..."Hello world!"].map(c=>c.charCodeAt().toString(2).padStart(8,0)).join``
75 bytes
for(i=s="";c="Hello world!".charCodeAt(i++);)s+=c.toString(2).padStart(8,0)
75 bytes
s="",f=n=>n>1?f(n>>1)+n%2:"";for(c of"Hello world!")s+=f(c.charCodeAt()|256)
76 bytes
i=s="";while(c="Hello world!".charCodeAt(i++))s+=c.toString(2).padStart(8,0)
76 bytes
s='';for(c of"Hello world!")s+=(("00"+c.charCodeAt().toString(2)).slice(-8))
76 bytes
i=s="";while(i^12)s+="Hello world!".charCodeAt(i++).toString(2).padStart(8,0)
77 bytes
for(c=i="";i<12;c+="Hello world!".charCodeAt(i++).toString(2).padStart(8,0));c
78 bytes
for(c='',i=0;i<12;)c+="Hello world!"[i++].charCodeAt().toString(2).padStart(8,0)
80 bytes
[..."Hello world!"].map(c=>c.charCodeAt()|256).map(f=n=>n>1?f(n>>1)+n%2:"").join``
82 bytes
[..."Hello world!"].map(f=n=>(n=~~n?n:256|n.charCodeAt(),n>1?f(n>>1)+n%2:"")).join``
84 bytesThere is a problem with your stringToBinary function. Converting a character to binary only leaves you with the least amount of bits. So you still need to convert it to an 8-bit string.
The other thing is, that you can just get the first 8 digits from your binary and trim your input as you go, like in the following example.
function stringToBinary(input) {
var characters = input.split('');
return characters.map(function(char) {
const binary = char.charCodeAt(0).toString(2)
const pad = Math.max(8 - binary.length, 0);
// Just to make sure it is 8 bits long.
return '0'.repeat(pad) + binary;
}).join('');
}
function binaryToString(input) {
let bytesLeft = input;
let result = '';
// Check if we have some bytes left
while (bytesLeft.length) {
// Get the first digits
const byte = bytesLeft.substr(0, 8);
bytesLeft = bytesLeft.substr(8);
result += String.fromCharCode(parseInt(byte, 2));
}
return result;
}
const binary = stringToBinary('test');
console.log({
binary,
text: binaryToString(binary),
});
First of all, you need to take the same length of the converted string as input for the conversion back to a string, by taking String#padStart with a length of 8 and a filling character of zero.
function stringToBinary(input) {
var characters = input.split('');
return characters
.map(function(char) {
return char.charCodeAt(0).toString(2).padStart(8, 0)
})
.join(' '); // show with space for each byte
// watch leading zero, which is missed in the former code
}
console.log(stringToBinary('test'))
The you need to take this string and split it into a length of eight characters and convert it back.
function binaryToString(input) {
return input
.match(/.{8}/g) // take 8 characters
.map(function(byte) {
return String.fromCharCode(parseInt(byte, 2));
})
.join('');
}
console.log(binaryToString('01110100011001010111001101110100'));
While you are asking for a faster way, you could spread the splitted converted bytes to the fromCharCode function.
function binaryToString(input) {
return String
.fromCharCode(...input
.match(/.{8}/g)
.map(byte => parseInt(byte, 2))
);
}
console.log(binaryToString('01110100011001010111001101110100'));
Use String.fromCharCode() and parseInt( , 2) like this:
const binary = `1010011 1110100 1100001 1100011 1101011
1001111 1110110 1100101 1110010 1100110
1101100 1101111 1110111`;
const outputStr = binary
// split string into an array of base 2 (binary) UTF-16 chars
.split(' ')
// map every binary char to a UTF-16 number of base 10
// and then get the string representation of that UTF-16 number
.map(bin => String.fromCharCode(parseInt(bin, 2)))
// join the array back to a single string
.join('');
console.log(outputStr);
String.fromCharCode(number)will return a String from a UTF-16 char codeparseInt(binary , 2)will transform a base 2 number string into a base 10 number
Edit:
As the String.fromCharCode() function accepts multiple chars as parameters, you could also use the Spread Operator (...) like so:
const binary = `1010011 1110100 1100001 1100011 1101011
1001111 1110110 1100101 1110010 1100110
1101100 1101111 1110111`;
const outputStr = String.fromCharCode(
...binary.split(' ').map(bin => parseInt(bin, 2))
)
console.log(outputStr);
Edit 2:
As this answer gets more traffic over time, I am going to also add the solution to do it the other way around too ... just in case:
const str = `StackOverflow`;
const outputStr = str.split('') // split in single chars
.map(c => c.charCodeAt(0) // get the UTF-16 code (10 base)
.toString(2)) // transform it back to a string (2 base)
.join(' ') // make single string from array
console.log(outputStr);
str ="01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111"
function binaryAgent(str) {
return str.split(' ').map(letter=>String.fromCharCode(parseInt(letter, 2))).join('')
}
console.log(binaryAgent(str))
First we use the .split() method to convert the string to array using the ' '(space character)
After that we use the .map() high-order loop method to iterate through each binary-code-letter
For each binary-code-letter we use String.fromCharCode() on parseInt('each letter',2)=> which converts the binary string to a number. The second argument "2" of the parseInt method which is called(radix) is to define which numeral system we want to use.
Finally we can join the manipulated array back together calling the join('') method but this time we don't use a space between
=======
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).
If you want to convert the array back to a string use join() (MDN) and for converting a string to an integer use parseInt() (MDN). The second argument of the later is an optional radix.
JavaScript will try to determine, what radix to use, but to be sure you should always add your radix manually. Citing from MDN:
If radix is undefined or 0, JavaScript assumes the following:
If the input string begins with "0x" or "0X", radix is 16 (hexadecimal).
If the input string begins with "0", radix is eight (octal). This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10). For this reason always specify a radix when using parseInt.
If the input string begins with any other value, the radix is 10 (decimal).
So in your case the following code should work:
var a = '01001011';
var b = parseInt( a.split('').reverse().join(''), 2 );
or just (if you would want to convert the starting string, without the reversal):
var b = parseInt( a, 2 );
Just call parseInt with a different radix, in this case use 2 for binary.
var a = parseInt("01001011", 2);
// a === 75
parseInt attempts to figure out the radix itself when you don't explicitly specify it. From the Mozilla Developer Network:
If radix is
undefinedor 0, JavaScript assumes the following:
- If the input
stringbegins with "0x" or "0X", radix is 16 (hexadecimal).- If the input
stringbegins with "0", radix is eight (octal). This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10). For this reason always specify a radix when usingparseInt.- If the input
stringbegins with any other value, the radix is 10 (decimal).
In this case, it is crucial that you do specify the radix, as otherwise it may be interpreted as either a decimal or an octal number. As a rule of thumb, always specify the radix.