1

What is idiomatic way to convert standard hexadecimal string (like "0x0123") to BigInteger in C#?

What I tried requires removing the hex prefix manually:

using System;
using System.Numerics;
using System.Globalization;

namespace TestHex
{
    class Program
    {
        static void Main(string[] args)
        {
            BigInteger A;
// it does not work
//            A = BigInteger.Parse("0x0123");
// it works, but without hex prefix
            A = BigInteger.Parse("123", NumberStyles.AllowHexSpecifier);
            Console.WriteLine(A);
            Console.ReadLine();
        }
    }
}
4

1 回答 1

4

根据MSDN 文档习惯用法是只接受十六进制字符串而不0x作为输入,然后通过输出前缀来欺骗用户0x

public class Example
{
    public static void Main()
    {
        string[] hexStrings = { "80", "E293", "F9A2FF", "FFFFFFFF", 
                                "080", "0E293", "0F9A2FF", "0FFFFFFFF",  
                                "0080", "00E293", "00F9A2FF", "00FFFFFFFF" };
        foreach (string hexString in hexStrings)
        {
            BigInteger number = BigInteger.Parse(
                hexString,
                NumberStyles.AllowHexSpecifier);
            Console.WriteLine("Converted 0x{0} to {1}.", hexString, number);
        }         
    }
}
// The example displays the following output: 
//       Converted 0x80 to -128. 
//       Converted 0xE293 to -7533. 
//       Converted 0xF9A2FF to -417025. 
//       Converted 0xFFFFFFFF to -1. 
//       Converted 0x080 to 128. 
//       Converted 0x0E293 to 58003. 
//       Converted 0x0F9A2FF to 16360191. 
//       Converted 0x0FFFFFFFF to 4294967295. 
//       Converted 0x0080 to 128. 
//       Converted 0x00E293 to 58003. 
//       Converted 0x00F9A2FF to 16360191. 
//       Converted 0x00FFFFFFFF to 4294967295.

这真是一个垃圾成语。我会发明适合您用例的您自己的成语。

于 2012-10-30T12:00:24.623 回答