有谁知道如何在Java中的特定位中生成数字? [英] Does anyone know how to generate a number within specific bits in Java?

查看:66
本文介绍了有谁知道如何在Java中的特定位中生成数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

但是我一直在想,如果我想随机产生一个100位的数字怎么办?我该如何使用BigInteger数据类型?

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?

推荐答案

新答案:

BigInteger类具有可用于生成

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:

java.util.Random类具有nextBytes方法,用于使用随机值填充字节数组.您可以使用它生成具有任意字节数的BigInteger.

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.

复杂的是,当位数不是8的倍数时该怎么办?我的建议是生成一个字节过多,并通过移位操作除去多余的位.

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

这篇关于有谁知道如何在Java中的特定位中生成数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆