【发布时间】:2016-12-15 20:35:24
【问题描述】:
如何将下面的 Java 行转换为 C#。它生成一个 130 位大小的随机 BigInteger,将其转换为以 32 为底的字符串(即 不是十进制),然后对字符串进行操作:
new BigInteger(130, new SecureRandom()).toString(32).replace("/", "w").toUpperCase(Locale.US);
如何在 C# 中实现这一点?
- 生成一个随机的 130 位 BigInteger
- 将其转换为以 32 为底的字符串
就随机 BigInteger 而言,我有这个功能:
static BigInteger RandomInteger(int bits)
{
RNGCryptoServiceProvider secureRandom = new RNGCryptoServiceProvider();
// make sure there is extra room for a 0-byte so our number isn't negative
// in the case that the msb is set
var bytes = new byte[bits / 8 + 1];
secureRandom.GetBytes(bytes);
// mask off excess bits
bytes[bytes.Length - 1] &= (byte)((1 << (bits % 8)) - 1);
return new BigInteger(bytes);
}
取自未解决基数 32 转换的问题:Equivalent of Java's BigInteger in C#
但是我不确定该函数是否也正确。
我目前的 C# 代码,RandomInteger 是上面描述的函数:
RandomInteger(130).ToString().Replace("/","w").ToUpper(CultureInfo.GetCultureInfo("en-US"));
【问题讨论】:
-
不清楚你在问什么。与其提供一个不完整的 Java 示例供其他人为您翻译,不如提供一个很好的 minimal reproducible example 来显示您目前拥有的 C# 代码,解释该代码的作用以及您希望它做什么反而。还要解释为什么stackoverflow.com/questions/21002856/… 不能完全解决您的问题。
-
@PeterDuniho,我补充了为什么它不能完全解决我的担忧和我的 C# 代码。
-
很清楚:如何在 C# 中生成转换为 base 32 的 130 位随机 BigInteger?
-
FWIW,@hl3mukkel 的实现确实更好。 C# 的 BigInteger 期望字节数组是二进制补码,如果设置了最高有效字节的最高位,则将其解释为负数,这对随机数不利。所以他在顶部添加了至少一个零字节。他对数组大小的计算也更好。
标签: java c# random biginteger base32