[英]Java's BigInteger C# in Base 32
如何將下面的Java代碼轉換為C#。 它生成大小為130位的隨機BigInteger,將其轉換為以32為底的字符串(即, 不是小數 ),然后操作該字符串:
new BigInteger(130, new SecureRandom()).toString(32).replace("/", "w").toUpperCase(Locale.US);
如何在C#中實現?
據隨機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轉換的問題: C#中Java的BigInteger的等效項
但是我不確定該功能是否正確。
到目前為止,我擁有的C#代碼是RandomInteger,它是上述函數:
RandomInteger(130).ToString().Replace("/","w").ToUpper(CultureInfo.GetCultureInfo("en-US"));
上面的代碼有很多錯誤,如果位全部為整數,則最后一個數字將被完全屏蔽掉,並且由於新的BigInteger(byte [])重載期望使用一個小端符號的數字,因此該數字有可能變為正數,因此您必須前面加上一個0字節
static BigInteger RandomInteger(int bits)
{
var bytes = new byte[(bits + 7) / 8 + 1];
using (var rng = new RNGCryptoServiceProvider())
rng.GetBytes(bytes, 0, bytes.Length - 1);
var remainingBits = bits % 8;
if (remainingBits > 0)
bytes[bytes.Length - 2] &= (byte)((1 << remainingBits) - 1);
return new BigInteger(bytes);
}
我想這會工作
這就是我要轉換為基數32的方式。請注意,我無法在此處進行測試,並且我的C#有點生銹,但是我認為以下內容足以使您順利進行(如果有人看到語法錯誤,請進行編輯出來):
static string BigIntegerToString32(BigInteger bi)
{
// Obvious shortcut -- avoids problems later on.
if (bi == BigInteger.Zero)
return("0");
readonly char[] digits = new char[] {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V'
};
// Only work with positive BigInteger.
BigInteger value = BigInteger.Abs(bi);
// Collects one digit on each iteration.
StringBuilder result = new StringBuilder();
// This value is needed more often -- only converted once.
BigInteger thirtyOne = 0x1F;
while (value > BigInteger.Zero)
{
// get next digit: value % 32
result.Insert(0, digits[(int)(value & thirtyOne)]);
// shift out last digit: value = value / 32
value >>= 5;
}
// prepend '-' if negative
if (bi < BigInteger.Zero)
result.Insert(0, '-');
return result.ToString();
}
請注意,對於龐大的BigIntegers
來說,使用更快但更復雜的算法可能是有意義的(就像我在Delphi BigInteger
實現中所做的那樣),盡管這大概是C#的BigInteger
(不使用更復雜的例程來實現)大型BigIntegers,AFAIK(與Java不同)也針對基數10執行了此操作。
@ hl3mukkel的答案比生成並發布的代碼在生成n
位隨機BigInteger
方面做得更好,因此請使用他的代碼生成這樣的BigInteger
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.