Missing bits - Text-to-Binary JS

Viewed 45

I am working on a code written from someone else. While examining the code I noticed that during the conversion there is 0 bit that gets removed. Here is an example of the code:

user_input = 'a'
        
input_bits = '';
for (let i = 0; i < user_input.length; i++) {
    input_bits += user_input.charCodeAt(i).toString(2);
}

When I run this code the value in input_bits is: 1100001. I used an online converter and the result is: 01100001. I think in my case missing bits is important because if i want to convert another string for example ab my version of the code will give 11000011100010 and the expected value should be 0110000101100010.

How can I fix that. I tried an if statement in the loop to append the missing 0 bits until the length is 8, but that lead to even stranger results.

Thank you in advance.

1 Answers

Just padStart with zeros to length 8:

user_input = 'a'
    
input_bits = '';
for (let i = 0; i < user_input.length; i++) {
    input_bits += user_input.charCodeAt(i).toString(2).padStart(8, "0");
}
console.log(input_bits)

Related