在C#中,如何在十六进制数和十进制数之间进行转换?
要将十进制转换为十六进制,请执行以下操作...
string hexValue = decValue.ToString("X");
要将十六进制转换为十进制,请执行以下操作...
int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
或者int decValue = Convert.ToInt32(hexValue, 16);
十六进制 -> 十进制:
Convert.ToInt64(hexString, 16);
十进制 -> 十六进制
string.Format("{0:x}", intValue);
Convert.ToInt64(hexValue, 16);
的好处在于它无论有没有0x
前缀都可以进行转换,而其他解决方案可能不行。 - Craig看起来你可以说
Convert.ToInt64(value, 16)
获取十六进制数的十进制表示方法。
反过来的方法是:
otherVar.ToString("X");
如果您希望在将十六进制转换为十进制数时获得最大性能,则可以使用预填充的十六进制到十进制值表的方法。
以下代码演示了这个想法。我的性能测试表明它比 Convert.ToInt32(...) 快20%-40%:
class TableConvert
{
static sbyte[] unhex_table =
{ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1
,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
};
public static int Convert(string hexNumber)
{
int decValue = unhex_table[(byte)hexNumber[0]];
for (int i = 1; i < hexNumber.Length; i++)
{
decValue *= 16;
decValue += unhex_table[(byte)hexNumber[i]];
}
return decValue;
}
}
// Store integer 182
int decValue = 182;
// Convert integer 182 as a hex in a string variable
string hexValue = decValue.ToString("X");
// Convert the hex string back to the number
int decAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
String stringrep = myintvar.ToString("X");
int num = int.Parse("FF", System.Globalization.NumberStyles.HexNumber);
请尝试在C#中使用BigNumber - 代表任意大的有符号整数。
using System.Numerics;
...
var bigNumber = BigInteger.Parse("837593454735734579347547357233757342857087879423437472347757234945743");
Console.WriteLine(bigNumber.ToString("X"));
4F30DC39A5B10A824134D5B18EEA3707AC854EE565414ED2E498DCFDE1A15DA5FEB6074AE248458435BD417F06F674EB29A2CFECF
ArgumentNullException - 值为null。
FormatException - 值不符合正确格式。
您可以将字符串转换并存储在BigNumber中,而无需担心数字大小的限制,除非该字符串为空且不包含字母。
如果是一个非常大的十六进制字符串,超出了普通整数的容量:
对于.NET 3.5,我们可以使用BouncyCastle的BigInteger类:
String hex = "68c7b05d0000000002f8";
// results in "494809724602834812404472"
String decimal = new Org.BouncyCastle.Math.BigInteger(hex, 16).ToString();
.NET 4.0有一个名为BigInteger的类,用于处理大整数。
十六进制转十进制
Convert.ToInt32(number, 16);
十进制转十六进制转换
int.Parse(number, System.Globalization.NumberStyles.HexNumber)
十进制 - 十六进制
var decValue = int.Parse(Console.ReadLine());
string hex = string.Format("{0:x}", decValue);
Console.WriteLine(hex);
十六进制 - 十进制(使用命名空间:using System.Globalization;)
var hexval = Console.ReadLine();
int decValue = int.Parse(hexval, NumberStyles.HexNumber);
Console.WriteLine(decValue);
int.Parse
没有选项让你指定基数为int
,只有一些有效的NumberStyles
选项。对于基数16,任何一个选项都可以,但作为一种通用解决方案,了解两种方法的工作原理是很好的。 - Tim S.