在Java中如何生成特定位数的数字,有人知道吗?

huangapple go评论76阅读模式
英文:

Does anyone know how to generate a number within specific bits in Java?

问题

这是生成从1到10的随机数的代码:

int a = (int)(Math.random() * 10) + 1;

但我一直在思考,如果我想生成一个具有100位的随机数,我该如何使用BigInteger数据类型来实现呢?

英文:

This is the code to generate a random number from 1 to 10:

int a = (int)(Math.random() * 10) + 1;

But I have been thinking, what if I want to generate a number that is 100 bits randomly? how can I do this with BigInteger datatype?

答案1

得分: 4

The BigInteger类有一个构造函数,您可以使用它来生成具有给定位数的随机数。这是您可以如何使用它的方式:

BigInteger random(int bits) {
    Random random = new Random();
    return new BigInteger(bits, random);
}
英文:

New answer:

The BigInteger class has a constructor that you can use to generate a random number with the given number of bits. This is how you could use it:

BigInteger random(int bits) {
    Random random = new Random();
    return new BigInteger(bits, random);
}

Old answer with a long-winded way of doing the same:

The java.util.Random class has a nextBytes method to fill an array of bytes with random values. You can use that to generate a BigInteger with an arbitrary number of bytes.

The complication is, what to do when number of bits isn't a multiple of 8? My suggestion is to generate one byte too much and get rid of the extra bits with a shift operation.

BigInteger random(int bits) {
    Random random = new Random();
    // One byte too many if not multiple of 8
    byte[] bytes = new byte[(bits + 7) / 8];
    random.nextBytes(bytes);
    BigInteger randomNumber = new BigInteger(1, bytes);
    // Get rid of extra bits if not multiple of 8
    return randomNumber.shiftRight(bytes.length*8 - bits);
}

huangapple
  • 本文由 发表于 2020年8月12日 18:31:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/63374677.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定