【问题标题】:Hexadecimal to BigInteger conversion十六进制到 BigInteger 的转换
【发布时间】:2012-10-19 17:59:30
【问题描述】:

在 C# 中将标准十六进制字符串(如“0x0123”)转换为 BigInteger 的惯用方法是什么?

我尝试的需要手动删除十六进制前缀:

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();
        }
    }
}

【问题讨论】:

  • 如果适合长,可以使用var A = new BigInteger(Convert.ToInt64("0x123", 16));
  • 嗯。对于那个枚举值来说,这是一个真的糟糕的名字。 “我们想要一个将数字解析为十六进制的值,但不允许他们将其指定为带有标准十六进制前缀的十六进制。我们称之为 AllowHexSpecifier!”
  • 您的问题不清楚,请澄清您要做什么。我除了一个拥有 15.9K 声望点的人提出的更详细的问题。整个以身作则的领导角色。

标签: c# hex biginteger


【解决方案1】:

根据MSDN documentation成语是只接受没有0x的十六进制字符串作为输入,然后通过输出前缀0x来欺骗用户: p>

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.

这是一个非常垃圾的成语。我会发明适合你用例的你自己的习语。

【讨论】:

    猜你喜欢
    • 2011-06-26
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    • 2018-12-12
    • 1970-01-01
    • 2012-12-12
    相关资源
    最近更新 更多