How to convert real number between 0 to 1 into binary in Javascript?

99 Views Asked by At

I am trying to convert a real number (a) which is between zero and one to an array of bits.

I have tried this:

let a = 0.625
let b = []
while (a != 0) {
    if ((a * 2) >= 1) {
        b.push(1)
        a = a - 1          
    }    
    else {
        b.push(0)  
    }
}
console.log(b)

But I get an error that says "something went wrong while displaying this webpage".

Can you help me? Thanks.

1

There are 1 best solutions below

1
On

Because you just test if a * 2 is larger 1, but never actually multiply it by two you enter a infinite loop. You could do:

let a = 0.625
let b = []
while (a != 0) {
    a *= 2

    if (a >= 1) {
        b.push(1)
        a = a - 1
        
    }
    
    else {
        b.push(0)

    }
}
console.log(b)