C# 如何在十六进制和十进制之间转换数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/74148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert numbers between hexadecimal and decimal
提问by Andy McCluggage
How do you convert between hexadecimal numbers and decimal numbers in C#?
C#中十六进制数和十进制数之间如何转换?
采纳答案by Andy McCluggage
To convert from decimal to hex do...
要将十进制转换为十六进制,请执行...
string hexValue = decValue.ToString("X");
To convert from hex to decimal do either...
要将十六进制转换为十进制,请执行以下任一操作...
int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
or
或者
int decValue = Convert.ToInt32(hexValue, 16);
回答by Sklivvz
String stringrep = myintvar.ToString("X");
int num = int.Parse("FF", System.Globalization.NumberStyles.HexNumber);
回答by Jesper Blad Jensen
It looks like you can say
好像可以说
Convert.ToInt64(value, 16)
to get the decimal from hexdecimal.
从十六进制得到十进制。
The other way around is:
另一种方式是:
otherVar.ToString("X");
回答by Rob
// 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);
回答by Jonathan Rupp
Hex -> decimal:
十六进制 -> 十进制:
Convert.ToInt64(hexValue, 16);
Decimal -> Hex
十进制 -> 十六进制
string.format("{0:x}", decValue);
回答by Ecstatic Coder
static string chex(byte e) // Convert a byte to a string representing that byte in hexadecimal
{
string r = "";
string chars = "0123456789ABCDEF";
r += chars[e >> 4];
return r += chars[e &= 0x0F];
} // Easy enough...
static byte CRAZY_BYTE(string t, int i) // Take a byte, if zero return zero, else throw exception (i=0 means false, i>0 means true)
{
if (i == 0) return 0;
throw new Exception(t);
}
static byte hbyte(string e) // Take 2 characters: these are hex chars, convert it to a byte
{ // WARNING: This code will make small children cry. Rated R.
e = e.ToUpper(); //
string msg = "INVALID CHARS"; // The message that will be thrown if the hex str is invalid
byte[] t = new byte[] // Gets the 2 characters and puts them in seperate entries in a byte array.
{ // This will throw an exception if (e.Length != 2).
(byte)e[CRAZY_BYTE("INVALID LENGTH", e.Length ^ 0x02)],
(byte)e[0x01]
};
for (byte i = 0x00; i < 0x02; i++) // Convert those [ascii] characters to [hexadecimal] characters. Error out if either character is invalid.
{
t[i] -= (byte)((t[i] >= 0x30) ? 0x30 : CRAZY_BYTE(msg, 0x01)); // Check for 0-9
t[i] -= (byte)((!(t[i] < 0x0A)) ? (t[i] >= 0x11 ? 0x07 : CRAZY_BYTE(msg, 0x01)) : 0x00); // Check for A-F
}
return t[0x01] |= t[0x00] <<= 0x04; // The moment of truth.
}
回答by Omair
This is not really easiest way but this source code enable you to right any types of octal number i.e 23.214, 23 and 0.512 and so on. Hope this will help you..
这不是最简单的方法,但此源代码使您可以正确处理任何类型的八进制数,即 23.214、23 和 0.512 等。希望能帮到你..
public string octal_to_decimal(string m_value)
{
double i, j, x = 0;
Int64 main_value;
int k = 0;
bool pw = true, ch;
int position_pt = m_value.IndexOf(".");
if (position_pt == -1)
{
main_value = Convert.ToInt64(m_value);
ch = false;
}
else
{
main_value = Convert.ToInt64(m_value.Remove(position_pt, m_value.Length - position_pt));
ch = true;
}
while (k <= 1)
{
do
{
i = main_value % 10; // Return Remainder
i = i * Convert.ToDouble(Math.Pow(8, x)); // calculate power
if (pw)
x++;
else
x--;
o_to_d = o_to_d + i; // Saving Required calculated value in main variable
main_value = main_value / 10; // Dividing the main value
}
while (main_value >= 1);
if (ch)
{
k++;
main_value = Convert.ToInt64(Reversestring(m_value.Remove(0, position_pt + 1)));
}
else
k = 2;
pw = false;
x = -1;
}
return (Convert.ToString(o_to_d));
}
回答by msanjay
If it's a really big hex string beyond the capacity of the normal integer:
如果它是一个超出正常整数容量的非常大的十六进制字符串:
For .NET 3.5, we can use BouncyCastle's BigInteger class:
对于 .NET 3.5,我们可以使用 BouncyCastle 的 BigInteger 类:
String hex = "68c7b05d0000000002f8";
// results in "494809724602834812404472"
String decimal = new Org.BouncyCastle.Math.BigInteger(hex, 16).ToString();
.NET 4.0 has the BigIntegerclass.
.NET 4.0 有BigInteger类。
回答by Luke Puplett
An extension method for converting a byte array into a hex representation. This pads each byte with leading zeros.
一种将字节数组转换为十六进制表示的扩展方法。这用前导零填充每个字节。
/// <summary>
/// Turns the byte array into its Hex representation.
/// </summary>
public static string ToHex(this byte[] y)
{
StringBuilder sb = new StringBuilder();
foreach (byte b in y)
{
sb.Append(b.ToString("X").PadLeft(2, "0"[0]));
}
return sb.ToString();
}
回答by Vadym Stetsiak
If you want maximum performance when doing conversion from hex to decimal number, you can use the approach with pre-populated table of hex-to-decimal values.
如果您希望在从十六进制数转换为十进制数时获得最高性能,您可以使用该方法与预先填充的十六进制到十进制值表。
Here is the code that illustrates that idea. My performance testsshowed that it can be 20%-40% faster than Convert.ToInt32(...):
这是说明该想法的代码。我的性能测试表明它可以比 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;
}
}