[英]In Java, is there a simple way to generate random N bits, but make sure that there is at least ONE bit equals 1 for all N bits?
As for N, it could be as large as 179. 至于N,则可能高达179。
For example, I was able to do it for n up to 32 bits: 例如,我能够做到n最多32位:
new Random().nextInt(2^n-1)+1
nextLong() is not possible because I can't pass a value to it and it only generates a random value up to 48-bit. nextLong()是不可能的,因为我无法将值传递给它,并且它仅生成一个随机值,最大为48位。
Use BigInteger to create a random number. 使用BigInteger创建一个随机数。 If it happens to be zero, try again.
如果恰好为零,请重试。
public static BigInteger randomForBitsNonZero(int numBits, Random r) {
BigInteger candidate = new BigInteger(numBits, r);
while(candidate.equals(BigInteger.ZERO)) {
candidate = new BigInteger(numBits, r);
}
return candidate;
}
This will be randomly distrubted about the number of bits. 这将随机分配有关位数的信息。 It is very unlikely that the if statement will ever trigger for a significantly high
numBits
but the protection is good for compelteness and because you might have low numBits
sometimes that would roll a 0 very often. 如果if语句触发一个非常高的
numBits
是不太可能的,但是这种保护对于numBits
很有好处,因为您的numBits
有时很低,有时会经常滚动为0。
You can use Random.nextBytes()
to generate as many random bytes as you want. 您可以使用
Random.nextBytes()
生成任意数量的随机字节。 The number of bytes you need is (number-of-bits + 1) / 8. 您需要的字节数是(位数+ 1)/ 8。
Then in order to ensure that at least one bit is set to 1, you can pick a bit, any bit, at random, and set it to 1, follows: 然后,为了确保至少一位设置为1,您可以随机选择一个位,然后将其设置为1,如下所示:
int bitIndex = random.nextInt( N );
int byteIndex = bitIndex / 8;
bitIndex = bitIndex % 8;
randomBytes[byteIndex] |= (1 << bitIndex);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.