Home > Enterprise >  How to convert each character to binary
How to convert each character to binary

Time:11-04

I have this problem, I would like to convert each character to a binary number according to an if 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 binarys 

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

CodePudding user response:

Split the number as a string and map over the digits:

const sum = 7466454644;

const string = sum.toString(); // convert to string

const result = string
    .split("")                 // split to digits
    .map((x) =>  ( x > 4))     // if digit is greater than 4 make it 1
    .join("");                 // join back into string
    
console.log(result);           // 1011010100

( x > 4) is very terse but is equivalent to Number(Number(x) > 4). We're converting a boolean to a number since it'll be 0 or 1.

CodePudding user response:

The idea is to get the last digit from the whole number in every iteration by last_digit = number 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 = 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!

  • Related