Search code examples
javascripthtmlbinarynumber-systems

how do i randomly generate a binary number in javascript?


I'm making a simple program where i make a number system conversion quiz but i don't know how to generate a binary number in Javascript.

the user chooses what kind of conversion he/she likes. (eg: binary to decimal, decimal to hex etc) it also asks how many questions the user wants and proceeds to generate the questions once the "make quiz" button is clicked.

this is what my program looks like: image

its still a very rough draft so its noot looking very good lol


Solution

  • You can use binary evaluation with prefix "0b". You're binary are strings but if you want the decimal value you just use Number(binary) type conversion.

    function randomDigit() {
      return Math.floor(Math.random() * Math.floor(2));
    }
    
    function generateRandomBinary(binaryLength) {
      let binary = "0b";
      for(let i = 0; i < binaryLength; ++i) {
        binary += randomDigit();
      }
      return binary;
    }
    
    const b = generateRandomBinary(6);
    console.log(b); // random binary number as a string ex: 0b101100
    console.log(Number(b)); // decimal value of this random binary number ex: 44

    You can also use prefix "0x" instead of "0b" for hexadecimal.