Binary string - JavaScript convert text to binary string

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?

This is from the FCC challenge: (“I love FreeCodeCamp!”)

01001001 00100000 01101100 01101111 01110110 01100101 00100000 01000110 01110010 01100101 01100101 01000011 01101111 01100100 01100101 01000011 01100001 01101101 01110000 00100001

This is from my code:

01001001 0100000 01101100 01101111 01110110 01100101 0100000 01000110 01110010 01100101 01100101 01000011 01101111 01100100 01100101 01000011 01100001 01101101 01110000 0100001

Seems like the challenge requires you to encode them in byte length. With that in mind, your assumption that prefixing any character returned from charCodeAt().toString(2) with ‘0’ is wrong. toString(2) returns the most efficient bit representation. For example, ‘!’ is 33 and its bit representation will only be 6 characters long. As a result, prefixing ‘0’ results 7 bits and that’s where your algorithm falls off.

2 Likes

I think I understand what you are saying… I am completely new at this, though.

I was trying to get it to return 8 characters. It obviously didn’t work this way. I edited it some more, and now it finally does, and it seems to be working with other online converters. It just seems kind of messy. I’ll get there eventually.