2

I need to convert a string to binary specifically on 7 bits.

'%'.charCodeAt().toString(2)

The above code return 100101, I think it convert on 8 bits. (so this link How to convert text to binary code in JavaScript? is not helping me).

% is equal to 0100101 in binary on 7 bits.

The only links I found on SO are about Java.

2
  • What if you calculate the length of the binary and if it less than 7 bin then add zero(s) at the left of the binary number? Commented Jul 6, 2020 at 17:09
  • @SajeebAhamed nice idea, i'm gonna try! Commented Jul 6, 2020 at 17:09

3 Answers 3

5

You can use the method String.prototype.padStart()

const sevenBitBinary = (char) => char.charCodeAt().toString(2).padStart(7, '0');

console.log(sevenBitBinary('%'));

Sign up to request clarification or add additional context in comments.

1 Comment

if char have ascii bigger than 128 ,it will show 8 bits
1

You can add 0s add the beginning with .padStart.

Comments

0

I think it can help you

function get7BitsBinaryString(number) {
  var result = '';
  var bits = [64, 32, 16, 8, 4, 2, 1];
  bits.forEach(bit => {
    if ((bit & number) === bit) {
      result += '1';
    } else {
      result += '0';
    }
  });
  return result;
}

console.log(get7BitsBinaryString('%'.charCodeAt()));

Comments

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.