2

number has num.toString(2)

I'm wondering if there's a way to take a string such as 'Hello world' and convert it to its ASCII binary representation.

Thanks!

1 Answer 1

10

You could utilize the charCodeAt() method.

First split the string, then map the characters to their respective character code using the charCodeAt method. From there, you can use .toString(2) to convert the integer to binary and the padStart() method to add leading zero padding.

'Hello world'.split('').map(c => c.charCodeAt().toString(2).padStart(8, '0')).join(' ');

Result:

"01001000 01100101 01101100 01101100 01101111 00100000 01110111 01101111 01110010 01101100 01100100"
Sign up to request clarification or add additional context in comments.

2 Comments

This is exactly what I'm looking for!
This works because the characters that ASCII has in common with Unicode (the C0 Controls and Basic Latin block) have single UTF-16 code units and those code units (16 bits) have the same values as in ASCII (8 bits). Without that chain of reasoning, the code is voodoo. See charCodeat, as linked in the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.