最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - how do i randomly generate a binary number in javascript? - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question asked Jul 16, 2020 at 11:23 léslés 393 silver badges11 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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.

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 es from a field, be sure you transform its value as number, via parseInt, before useing .toString(radix)

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));

发布评论

评论列表(0)

  1. 暂无评论