将整数转换为十六进制,然后再转换回来

如何转换以下内容?

2934(整数)到B76(十六进制)

让我解释一下我要做什么。我的数据库中有以整数形式存储的用户id。而不是让用户引用他们的id,我想让他们使用十六进制值。主要原因是它比较短。

所以我不仅需要从整数变成十六进制还需要从十六进制变成整数。

在c#中有简单的方法来做到这一点吗?

740870 次浏览

使用:

int myInt = 2934;
string myHex = myInt.ToString("X");  // Gives you hexadecimal
int myNewInt = Convert.ToInt32(myHex, 16);  // Back to int again.

更多信息和示例请参见如何:在十六进制字符串和数字类型之间转换(c#编程指南)

string HexFromID(int ID)
{
return ID.ToString("X");
}


int IDFromHex(string HexID)
{
return int.Parse(HexID, System.Globalization.NumberStyles.HexNumber);
}

但我真的怀疑这东西的价值。你的目标是使值更短,这是可以做到的,但这本身并不是一个目标。你的意思是要么让它更容易记,要么让它更容易打。

如果你的意思是更容易记住,那么你就后退了一步。我们知道它的大小是一样的,只是编码不同了。但是你的用户不会知道这些字母被限制为“A-F”,所以ID对他们来说将占据相同的概念空间,就像字母“A-Z”被允许一样。因此,它不像记忆电话号码,而更像记忆GUID(相同长度)。

如果你指的是打字,用户现在必须使用键盘的主要部分,而不是能够使用小键盘。打字可能会更困难,因为他们的手指不认识这个词。

一个更好的选择是让他们选择一个真实的用户名。

尝试以下将其转换为十六进制

public static string ToHex(this int value) {
return String.Format("0x{0:X}", value);
}

然后再回来

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

从# EYZ0


提示(来自评论):

使用.ToString("X4")来获得前导0的4位数字,或者使用.ToString("x4")来获得小写的十六进制数字(同样用于更多数字)。

十六进制:

string hex = intValue.ToString("X");

整数:

int intValue = int.Parse(hex, System.Globalization.NumberStyles.HexNumber)
int valInt = 12;
Console.WriteLine(valInt.ToString("X"));  // C  ~ possibly single-digit output
Console.WriteLine(valInt.ToString("X2")); // 0C ~ always double-digit output

在我找到这个答案之前,我创建了自己的解决方案,将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;
}

计时代码:

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

结果:

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

整数到十六进制:

Int a = 72;

Console.WriteLine(“{0:X}“,a);

十六进制到整型:

int b = 0xB76;

Console.WriteLine (b);

微软网络框架

解释得很好,编程行很少 好< / p >

// 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#

http://files.hddguru.com/download/Software/Seagate/St_mem.pas

从老式的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;
}
}

打印十六进制值的整数与零填充(如果需要):

int intValue = 1234;


Console.WriteLine("{0,0:D4} {0,0:X3}", intValue);

https://learn.microsoft.com/en-us/dotnet/standard/base-types/how-to-pad-a-number-with-leading-zeros

就像@Joel C一样,我认为这是一个AB问题。 有一个现有的算法,我认为更适合的需求,如所描述的,那就是uuencode,我相信它有许多公共领域的实现,也许调整以消除看起来非常类似于0/O的字符。很可能产生明显更短的字符串。我认为这是URL缩短器使用的