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.

PierreD
  • 860
  • 1
  • 14
  • 30

3 Answers3

5

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

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

console.log(sevenBitBinary('%'));
JardonS
  • 427
  • 3
  • 12
Sajeeb Ahamed
  • 6,070
  • 2
  • 21
  • 30
1

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

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
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()));
Ehsan Nazeri
  • 771
  • 1
  • 6
  • 10