0

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.

Artemis
  • 2,553
  • 7
  • 21
  • 36
  • Don't spam tags. Removing the `c` tag as there is _no_ C code here. – Craig Estey May 31 '22 at 18:25
  • @CraigEstey nor is there Java code. And Xcode is straight wrong, it's an editor typically for Apple tech, like Swift. While web-development server has absolutely nothing to do with anyting. It's not even an application where you *might* write code. – VLAZ May 31 '22 at 18:27
  • By `a = 0.625` initial value, it is an **endless loop**. `while` condition never become **zero** to break the loop. You should use a condition like `a > 0` for `while` loop. – Mehdi Rahimi May 31 '22 at 18:43

1 Answers1

0

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)