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 Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-program-to-convert-a-string-to-binary
JavaScript Program to Convert a String to Binary - GeeksforGeeks
July 10, 2024 - Then, we will convert each Base64 character to its binary form, ensuring that the final binary representation is accurate. ... Base64 Encoding: Use JavaScript's btoa() method to encode the string in Base64 format.
Discussions

[AskJS] Shortest way to convert string to 8-bit binary?
If you found those answers on SE's CodeGolf you are probably not going to get anything more golfed. The JavaScript golfers on that board get busy. More on reddit.com
🌐 r/javascript
20
7
April 14, 2024
javascript - Converting a string into binary and back - Stack Overflow
I got an assignment to convert a given string into binary and back to a string again. More on stackoverflow.com
🌐 stackoverflow.com
Binary string - JavaScript convert text to binary string - The freeCodeCamp Forum
I just finished ‘Binary Agent’, and I am trying to write a function that converts text to a binary string. I took the examples from this challenge to compare to the output from mine. It seems to be a bit off… missing some zeros. Could anyone help me fix this? More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
March 7, 2017
Binary to String in JavaScript - Stack Overflow
I have created a JavaScript program to convert a string into binary. Input: StackOverflow Output: 1010011 1110100 1100001 1100011 1101011 1001111 1110110 1100101 1110010 1100110 1101100 1101111 More on stackoverflow.com
🌐 stackoverflow.com
🌐
TutorialsPoint
tutorialspoint.com › article › string-to-binary-in-javascript
String to binary in JavaScript
March 15, 2026 - Converting strings to binary in JavaScript is straightforward using charCodeAt() and toString(2).
🌐
Reddit
reddit.com › r/javascript › [askjs] shortest way to convert string to 8-bit binary?
r/javascript on Reddit: [AskJS] Shortest way to convert string to 8-bit binary?
April 14, 2024 -

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 bytes
🌐
TutorialsPoint
tutorialspoint.com › converting-string-to-a-binary-string-javascript
Converting string to a binary string - JavaScript
const str = 'Hello worlld how are you'; const stringToBinary = (str = '') => { const s = str.toLowerCase(); let res = ''; for(let i = 0; i < s.length; i++){ // for special characters if(s[i].toLowerCase() === s[i].toUpperCase()){ res += s[i]; continue; }; if(s[i] > 'm'){ res += 1; }else{ res += 0; }; }; return res; }; console.log(stringToBinary(str));
Author: s-faisal
🌐
Online String Tools
onlinestringtools.com › convert-string-to-binary
Convert a String to Binary – Online String Tools
All our tools share the same user interface so as soon as you learn how to use one of the tools, you'll instantly know how to use all of them. Our online string tools are actually powered by our web developer tools that we created over the last couple of years. Check them out! ... All conversions and calculations are done in your browser using JavaScript.
Find elsewhere
Top answer
1 of 3
5

There 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),
});

2 of 3
0

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'));

🌐
freeCodeCamp
forum.freecodecamp.org › t › binary-string-javascript-convert-text-to-binary-string › 94421
Binary string - JavaScript convert text to binary string - The freeCodeCamp Forum
March 7, 2017 - I just finished 'Binary Agent', and I am trying to write a function that converts text to a binary string. I took the examples from this challenge to compare to the output from mine. It seems to be a bit off... missing s…
Top answer
1 of 3
26

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 code
  • parseInt(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);

2 of 3
2

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

=======

🌐
Sling Academy
slingacademy.com › article › javascript-convert-a-string-to-binary
JavaScript: Convert a String to Binary (2 Approaches) - Sling Academy
In this approach, we will use the TextEncoder API to encode the string into bytes and then convert each byte to binary using Uint8Array and toString(2).
🌐
DEV Community
dev.to › austinbh › binary-conversion-3mc4
Binary Conversion in JavaScript - DEV Community
October 28, 2019 - But wait, there is an optional argument for the parseInt function that allows us to specify the base to be used when converting a string to an integer. While this does allow us to specify that we are parsing the string into binary, we do not preserve the entire binary sequence but just the first bit.
🌐
Reality Ripple
udn.realityripple.com › docs › Web › API › DOMString › Binary
Binary strings - Web APIs
Its purpose however is not to represent characters, but binary data. The size of the data so represented is twice as big as it would be in normal binary format, however this will not be visible to the final user, since the length of JavaScript strings is calculated using two bytes as the unit.
Top answer
1 of 16
47

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"
2 of 16
31

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).

🌐
GitHub
github.com › orgs › community › discussions › 68852
How to get binary string in js · community · Discussion #68852
September 30, 2023 - JavaScript doesn't provide native capabilities to work with bits and bytes directly like some other programming languages. However, you can use some built-in functions and operators to work with binary data at the bit level.
🌐
Programiz
programiz.com › javascript › examples › decimal-binary
JavaScript Program to Convert Decimal to Binary
Enter a decimal number: 9 Binary: 1001 · In the above program, the user is prompted to enter a number. 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).
Top answer
1 of 4
80

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 );
2 of 4
39

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 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).

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.

🌐
GitHub
github.com › ibrod83 › javascript-binary-converter
GitHub - ibrod83/javascript-binary-converter · GitHub
If you have a "hex string"(as opposed to a JS Number in hex notation), you can import the HexStringConverter directly(you cannot use the generic converter function for this) const {HexStringConverter} = require('javascript-binary-converter'); const integer = new HexStringConverter('FFF4').toInteger() //65524 ·
Author: ibrod83