Search code examples
javascriptarraysbinarynumbersconverters

How to convert each character to binary


I have this problem, I would like to convert each character to a binary number according to an if the condition or another easier way. All numbers greater than or equal to 5 must convert to 1 and numbers less than or equal to 4 convert to 0.

Whole code:

n = [
  '0110100000', '1001011111',
  '1110001010', '0111010101',
  '0011100110', '1010011001',
  '1101100100', '1011010100',
  '1001100111', '1000011000'
] // array of binary 

let bin = [] // converting to numbers
length = n.length;
for (var i = 0; i < length; i++)
  bin.push(parseInt(n[i]));

var sum = 0; // sum of all binaries
for (var i = 0; i < bin.length; i++) {
  sum += bin[i];
}
console.log(sum); // 7466454644

// ...
// code converting each character
// ...

// console.log(sumConverted) // 1011010100

How do I convert each character >= 5 to 1, and the <5 to 0?

ex:

7466454644
7=1, 4=0, 6=1, 6=1, 4=0, 5=1, 4=0, 6=1, 4=0, 4=0
return 1011010100

Solution

  • The idea is to get the last digit from the whole number in every iteration by last_digit = number%10 and then remove the last digit from the original number as number = Math.ceil(number/10) and do it until the number is equal to 0

    for example:

    number = 123;
    last_digit = 123%10 = 3
    number = Math.ceil(number/10) = 12
    

    let num = 7466454644;
    
    let convertedBinary = '';
    while (num) {
      const number = (num % 10) < 5 ? 0 : 1;
      convertedBinary = `${number}${convertedBinary}`;
      num = Math.floor(num/10);
    }
    
    console.log(convertedBinary);

    Hope it helps!