lés
lés

Reputation: 39

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

Upvotes: 0

Views: 2577

Answers (3)

BSYoann
BSYoann

Reputation: 146

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.

Upvotes: 4

Andrea Giammarchi
Andrea Giammarchi

Reputation: 3198

You can use the parseInt function and pass a radix:

parseInt('101010', 2);   // 42
parseInt('101010', 16);  //1052688
parseInt('101010', 10);  // 101010

To convert any number to a different radix you can use toString(radix)

(42).toString(2);       // '101010'
(1052688).toString(16); // '101010'
(101010).toString(10);  // '101010'

If the input comes from a field, be sure you transform its value as number, via parseInt, before useing .toString(radix)

Upvotes: 4

Mohsen Alyafei
Mohsen Alyafei

Reputation: 5577

This function will return a random Binary Number output between the min and max numbers specified as entry parameters.

function randomBinary(min, max) {
  return Math.floor(min + Math.random() * (max + 1 - min)).toString(2);
}


// test examples

console.log(randomBinary(0,200000));
console.log(randomBinary(100,500));
console.log(randomBinary(0,300000));

Upvotes: 1

Related Questions