[英]BigInt from Javascript in C# equivalent
我用 Javascript 編寫了一個腳本,它將字符串轉換為 BigInt:
BigInt("0x40000000061c924300441104148028c80861190a0ca4088c144020c60c831088")
結果是: 28948022309972676171332135370609260321582865398090858033119816311589805691016
我需要找到與此函數等效的 C#。 我試過了:
Convert.ToInt64("0x40000000061c924300441104148028c80861190a0ca4088c144020c60c831088")
和BigInteger.Parse("0x40000000061c924300441104148028c80861190a0ca4088c144020c60c831088",NumberStyles.Any)
但兩者都拋出異常:無法解析該值。
有沒有人知道,什么函數可以從字符串中獲取結果,例如 JS 中的 BigInt()?
應該使用 ToString() 方法將其轉換回字符串格式,並且您需要在“R”的 ToString 中傳遞參數,該參數告訴它輸出 BigInteger 作為自身。
這是來自文檔:
“在大多數情況下,ToString 方法支持 50 個十進制數字的精度。也就是說,如果 BigInteger 值超過 50 個數字,則輸出字符串中僅保留 50 個最高有效數字;所有其他數字都替換為零。但是, BigInteger 支持 "R" 標准格式說明符,用於往返數值。由 ToString(String) 方法返回的帶有 "R" 格式字符串的字符串保留整個 BigInteger 值,然后可以使用Parse 或 TryParse 方法來恢復其原始值而不會丟失任何數據。”
您可能想嘗試使用“R”而不是“N”。
有關更多信息和示例,請參閱此內容:
您需要刪除前導“0x”來解析十六進制。
private static BigInteger? ParseBigInteger(string input) {
if (input.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) {
if (BigInteger.TryParse(input.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out var bigInt)) {
return bigInt;
}
}
else if (BigInteger.TryParse(input, NumberStyles.Any, CultureInfo.InvariantCulture, out var bigInt)) {
return bigInt;
}
return null;
}
//invocation
var bigInt = ParseBigInteger("0x40000000061c924300441104148028c80861190a0ca4088c144020c60c831088");
// => result: 28948022309972676171332135370609260321582865398090858033119816311589805691016
它對應於 long(或 Int64),一個 64 位整數
參考: https : //www.education.io/edpresso/what-is-a-bigint-in-javascript
您需要從字符串中刪除 'x' 字符並允許使用十六進制說明符,然后它將起作用:
BigInteger.Parse("0x40000000061c924300441104148028c80861190a0ca4088c144020c60c831088".Replace("x", string.Empty), NumberStyles.AllowHexSpecifier);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.