C# 将整数转换为十六进制并再次返回
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1139957/
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
Convert integer to hexadecimal and back again
提问by codette
How can I convert the following?
如何转换以下内容?
2934 (integer) to B76 (hex)
2934(整数)到 B76(十六进制)
Let me explain what I am trying to do. I have User IDs in my database that are stored as integers. Rather than having users reference their IDs I want to let them use the hex value. The main reason is because it's shorter.
让我解释一下我正在尝试做什么。我的数据库中有存储为整数的用户 ID。我想让他们使用十六进制值,而不是让用户引用他们的 ID。主要原因是因为它更短。
So not only do I need to go from integer to hex but I also need to go from hex to integer.
所以我不仅需要从整数到十六进制,而且我还需要从十六进制到整数。
Is there an easy way to do this in C#?
在 C# 中是否有一种简单的方法可以做到这一点?
采纳答案by Gavin Miller
// Store integer 182
int intValue = 182;
// Convert integer 182 as a hex in a string variable
string hexValue = intValue.ToString("X");
// Convert the hex string back to the number
int intAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
from http://www.geekpedia.com/KB8_How-do-I-convert-from-decimal-to-hex-and-hex-to-decimal.html
来自http://www.geekpedia.com/KB8_How-do-I-convert-from-decimal-to-hex-and-hex-to-decimal.html
回答by Scott Ivey
Use:
用:
int myInt = 2934;
string myHex = myInt.ToString("X"); // Gives you hexadecimal
int myNewInt = Convert.ToInt32(myHex, 16); // Back to int again.
See How to: Convert Between Hexadecimal Strings and Numeric Types (C# Programming Guide)for more information and examples.
有关更多信息和示例,请参见如何:在十六进制字符串和数字类型之间转换(C# 编程指南)。
回答by Joel Coehoorn
string HexFromID(int ID)
{
return ID.ToString("X");
}
int IDFromHex(string HexID)
{
return int.Parse(HexID, System.Globalization.NumberStyles.HexNumber);
}
I really question the value of this, though. You're stated goal is to make the value shorter, which it will, but that isn't a goal in itself. You really mean either make it easier to remember or easier to type.
不过,我真的很怀疑它的价值。你说的目标是使价值更短,它会的,但这本身并不是一个目标。你的意思是要么让它更容易记住,要么更容易打字。
If you mean easier to remember, then you're taking a step backwards. We know it's still the same size, just encoded differently. But your users won't know that the letters are restricted to 'A-F', and so the ID will occupy the same conceptual space for them as if the letter 'A-Z' were allowed. So instead of being like memorizing a telephone number, it's more like memorizing a GUID (of equivalent length).
如果你的意思是更容易记住,那么你就倒退了一步。我们知道它仍然是相同的大小,只是编码不同。但是您的用户不会知道字母仅限于“A-F”,因此 ID 将占据与他们相同的概念空间,就像允许使用字母“AZ”一样。因此,与其像记住电话号码,不如记住一个 GUID(等长)。
If you mean typing, instead of being able to use the keypad the user now must use the main part of the keyboard. It's likely to be more difficult to type, because it won't be a word their fingers recognize.
如果您的意思是打字,那么用户现在必须使用键盘的主要部分,而不是能够使用小键盘。打字可能会更困难,因为他们的手指不会识别出这个词。
A much better option is to actually let them pick a real username.
一个更好的选择是让他们选择一个真正的用户名。
回答by JaredPar
Try the following to convert it to hex
尝试以下将其转换为十六进制
public static string ToHex(this int value) {
return String.Format("0x{0:X}", value);
}
And back again
然后再回来
public static int FromHex(string value) {
// strip the leading 0x
if ( value.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) {
value = value.Substring(2);
}
return Int32.Parse(value, NumberStyles.HexNumber);
}
回答by Brandon
To Hex:
十六进制:
string hex = intValue.ToString("X");
To int:
输入:
int intValue = int.Parse(hex, System.Globalization.NumberStyles.HexNumber)
回答by user2179382
int valInt = 12;
Console.WriteLine(valInt.ToString("X")); // C ~ possibly single-digit output
Console.WriteLine(valInt.ToString("X2")); // 0C ~ always double-digit output
回答by Eric Helms
I created my own solution for converting int to Hex string and back before I found this answer. Not surprisingly, it's considerably faster than the .net solution since there's less code overhead.
在找到这个答案之前,我创建了自己的解决方案,用于将 int 转换为十六进制字符串并返回。毫不奇怪,它比 .net 解决方案快得多,因为代码开销更少。
/// <summary>
/// Convert an integer to a string of hexidecimal numbers.
/// </summary>
/// <param name="n">The int to convert to Hex representation</param>
/// <param name="len">number of digits in the hex string. Pads with leading zeros.</param>
/// <returns></returns>
private static String IntToHexString(int n, int len)
{
char[] ch = new char[len--];
for (int i = len; i >= 0; i--)
{
ch[len - i] = ByteToHexChar((byte)((uint)(n >> 4 * i) & 15));
}
return new String(ch);
}
/// <summary>
/// Convert a byte to a hexidecimal char
/// </summary>
/// <param name="b"></param>
/// <returns></returns>
private static char ByteToHexChar(byte b)
{
if (b < 0 || b > 15)
throw new Exception("IntToHexChar: input out of range for Hex value");
return b < 10 ? (char)(b + 48) : (char)(b + 55);
}
/// <summary>
/// Convert a hexidecimal string to an base 10 integer
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private static int HexStringToInt(String str)
{
int value = 0;
for (int i = 0; i < str.Length; i++)
{
value += HexCharToInt(str[i]) << ((str.Length - 1 - i) * 4);
}
return value;
}
/// <summary>
/// Convert a hex char to it an integer.
/// </summary>
/// <param name="ch"></param>
/// <returns></returns>
private static int HexCharToInt(char ch)
{
if (ch < 48 || (ch > 57 && ch < 65) || ch > 70)
throw new Exception("HexCharToInt: input out of range for Hex value");
return (ch < 58) ? ch - 48 : ch - 55;
}
Timing code:
计时码:
static void Main(string[] args)
{
int num = 3500;
long start = System.Diagnostics.Stopwatch.GetTimestamp();
for (int i = 0; i < 2000000; i++)
if (num != HexStringToInt(IntToHexString(num, 3)))
Console.WriteLine(num + " = " + HexStringToInt(IntToHexString(num, 3)));
long end = System.Diagnostics.Stopwatch.GetTimestamp();
Console.WriteLine(((double)end - (double)start)/(double)System.Diagnostics.Stopwatch.Frequency);
for (int i = 0; i < 2000000; i++)
if (num != Convert.ToInt32(num.ToString("X3"), 16))
Console.WriteLine(i);
end = System.Diagnostics.Stopwatch.GetTimestamp();
Console.WriteLine(((double)end - (double)start)/(double)System.Diagnostics.Stopwatch.Frequency);
Console.ReadLine();
}
Results:
结果:
Digits : MyCode : .Net
1 : 0.21 : 0.45
2 : 0.31 : 0.56
4 : 0.51 : 0.78
6 : 0.70 : 1.02
8 : 0.90 : 1.25
回答by novice
int to hex:
整数到十六进制:
int a = 72;
Console.WriteLine("{0:X}", a);
整数 a = 72;
Console.WriteLine("{0:X}", a);
hex to int:
十六进制到整数:
int b = 0xB76;
Console.WriteLine(b);
int b = 0xB76;
Console.WriteLine(b);
回答by JAAR
NET FRAMEWORK
网络框架
Very well explained and few programming lines GOOD JOB
很好的解释和很少的编程线 干得好
// Store integer 182
int intValue = 182;
// Convert integer 182 as a hex in a string variable
string hexValue = intValue.ToString("X");
// Convert the hex string back to the number
int intAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
PASCAL >> C#
帕斯卡 >> C#
http://files.hddguru.com/download/Software/Seagate/St_mem.pas
http://files.hddguru.com/download/Software/Seagate/St_mem.pas
Something from the old school very old procedure of pascal converted to C #
来自旧学校非常古老的 pascal 程序的东西转换为 C#
/// <summary>
/// Conver number from Decadic to Hexadecimal
/// </summary>
/// <param name="w"></param>
/// <returns></returns>
public string MakeHex(int w)
{
try
{
char[] b = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
char[] S = new char[7];
S[0] = b[(w >> 24) & 15];
S[1] = b[(w >> 20) & 15];
S[2] = b[(w >> 16) & 15];
S[3] = b[(w >> 12) & 15];
S[4] = b[(w >> 8) & 15];
S[5] = b[(w >> 4) & 15];
S[6] = b[w & 15];
string _MakeHex = new string(S, 0, S.Count());
return _MakeHex;
}
catch (Exception ex)
{
throw;
}
}
回答by Siva
Print integer in hex-value with zero-padding (if needed) :
用零填充以十六进制值打印整数(如果需要):
int intValue = 1234;
Console.WriteLine("{0,0:D4} {0,0:X3}", intValue);
https://docs.microsoft.com/en-us/dotnet/standard/base-types/how-to-pad-a-number-with-leading-zeros
https://docs.microsoft.com/en-us/dotnet/standard/base-types/how-to-pad-a-number-with-leading-zeros