我正在尝试使用以下代码生成 1024 位随机数:
var bytes = RandomNumberGenerator.GetBytes(128);
var number = new BigInteger(bytes);
但是当我使用 BigInteger 方法检查我的
number
时,它的 BitLength 总是不同的。
例如,运行此代码时:
for (int i = 0; i < 5; i++)
{
var bi = new BigInteger(RandomNumberGenerator.GetBytes(128));
Console.WriteLine($"{i}: {bi.GetBitLength()} bits | {bi.GetByteCount()} bytes");
}
我得到这个输出:
0: 1021 bits | 128 bytes
1: 1023 bits | 128 bytes
2: 1022 bits | 128 bytes
3: 1021 bits | 128 bytes
4: 1022 bits | 128 bytes
我在这里做错了什么/不理解吗?
GetBitLength
记录为:
获取当前实例的最短二进制补码表示(不带符号位)所需的位数。
还有,有帮助的是:
对于正整数,返回值等于普通的二进制表示字符串长度。
现在,考虑两个(非常小的)
BigInteger
值 - 1 和 3。只需要 1 位来表示整数值 1,而需要 2 位来表示整数 3。
实际上,任何可能在原始字节数组中传递的前导 0 位都不包含在
GetBitLength()
中。
我怀疑这对你来说绝对没问题。换句话说:如果您只想要 4 位数字,您想要 0 到 15 之间的值,还是 8 到 15 之间的值?因为要求
GetBitLength()
返回 4 会让你生成后者......(这实际上是“3 个随机位和一个始终为 1 的前导位”。)