kludg
kludg

Reputation: 27493

Hexadecimal to BigInteger conversion

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

Upvotes: 1

Views: 4882

Answers (1)

Rawling
Rawling

Reputation: 50114

According to the MSDN documentation, the idiom is to only accept hexadecimal strings without 0x as input, but then to lie to the user by outputting them prefixed with 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.

That's a really rubbish idiom. I'd invent your own idiom that fits your use case.

Upvotes: 4

Related Questions