在C#十六进制转换为十进制:
BigInteger number = BigInteger.Parse(hexString, NumberStyles.AllowHexSpecifier);
或者
BigInteger number = BigInteger.Parse(hexString, NumberStyles.HexNumber);
HexNumber是一个组合的NumberStyles,它是由AllowHexSpecifier,AllowLeadingWhite和AllowTrailingWhite组合而成,它允许字符串前后后空格。
使用BigInteger.Parse()转换十六进制的字符串为十进制的数字有两个注意点:
- 十六进制的字符串不能以“0x”或者“&h”为前缀
- 如果十六进制字符串的前两位的数等于或者大于0x80,那么Parse()方法会把第一位作为符号位,即把它存储为负数。如果需要把此十六进制的字符串解析为正数,需要在字符串前加上“0”。
示例
using System;
using System.Globalization;
using System.Numerics;
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("0x{0}:{1}.", hexString, number);
}
}
}
输出结果:
0x80:-128
0xE293:-7533
0xF9A2FF:-417025
0xFFFFFFFF:-1
0x080:128
0x0E293:58003
0x0F9A2FF:16360191
0x0FFFFFFFF:4294967295
0x0080:128
0x00E293:58003
0x00F9A2FF:16360191
0x00FFFFFFFF:4294967295