C#将整数转换为十六进制,然后再返回

cod*_*tte 441 c# hex type-conversion

我该如何转换以下内容?

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

让我解释一下我想做什么.我的数据库中有用户ID,存储为整数.我没有让用户引用他们的ID,而是让他们使用十六进制值.主要原因是因为它更短.

因此,我不仅需要从整数到十六进制,而且还需要从十六进制到整数.

有没有一种简单的方法在C#中执行此操作?

Gav*_*ler 822

// 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);
Run Code Online (Sandbox Code Playgroud)

来自http://www.geekpedia.com/KB8_How-do-I-convert-from-decimal-to-hex-and-hex-to-decimal.html

  • 您还可以使用以下命令指定位数:decValue.ToString("X4") (176认同)
  • 由于此处未提及:如果使用lowecase x(例如ToString("x4)",则会得到小写的十六进制值(例如b76). (77认同)
  • 我是唯一一个难以容忍变量名称"decValue"的人,因为它根本不是小数?对不起,我知道它来自其他来源,但stackoverflow应该比那更好. (13认同)
  • @bonitzenator大声笑,在这个答案存在的6年里,我从来没有注意到这一点.更新! (8认同)

Sco*_*vey 105

使用:

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

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


Jar*_*Par 55

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

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

又回来了

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 或"0x"位,这是OP并不真正想要的东西 (9认同)
  • (我很抱歉,我评论过).问题是"如何将2934转换为B76".其他答案确实只提供了解决方案的一半,但是您将"2934"转换为"0xB76".这根本不是一个糟糕的解决方案,但它并不能解决所提出的问题. (8认同)
  • 我更正了格式拼写 - 但没有downvote.没有任何解释的downvotes也让我脾气暴躁...... (3认同)

小智 19

int valInt = 12;
Console.WriteLine(valInt.ToString("X"));  // C  ~ possibly single-digit output 
Console.WriteLine(valInt.ToString("X2")); // 0C ~ always double-digit output
Run Code Online (Sandbox Code Playgroud)


Joe*_*orn 18

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

int IDFromHex(string HexID)
{
    return int.Parse(HexID, System.Globalization.NumberStyles.HexNumber);
}
Run Code Online (Sandbox Code Playgroud)

不过,我真的质疑这个的价值.你所说的目标是让价值更短,但它本身并不是一个目标.你的意思是要么让它更容易记忆,要么更容易打字.

如果你的意思更容易记住,那么你就会倒退一步.我们知道它仍然是相同的大小,只是编码不同.但是您的用户不会知道这些字母仅限于'A-F',因此ID将占用相同的概念空间,就像允许使用字母'AZ'一样.因此,不像记忆电话号码,更像是记忆GUID(等长).

如果您的意思是键入,而不是能够使用键盘,用户现在必须使用键盘的主要部分.输入可能会更加困难,因为它不会被他们的手指识别出来.

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

  • 迟来的响应,但是 - 一个从不包含负数的32位(带符号)int具有31位分辨率,而不是16位.您可以将其填充为一个unicode字符,但是当它是UTF8编码时,除非它在0到127之间它会占用比十六进制等值更多的字符.HEX对于这个问题并不是一个糟糕的解决方案,但int中四个字节的base64会更短(你可以修剪填充) (5认同)
  • 在这种情况下,您应该考虑二进制表示.这可能是32位int,只是不使用负部分,意味着16位分辨率.你可以很容易地把它放在一个unicode字符中. (3认同)

Bra*_*don 14

至十六进制:

string hex = intValue.ToString("X");
Run Code Online (Sandbox Code Playgroud)

到int:

int intValue = int.Parse(hex, System.Globalization.NumberStyles.HexNumber)
Run Code Online (Sandbox Code Playgroud)


小智 7

在找到这个答案之前,我创建了自己的解决方案,用于将int转换为Hex字符串.毫不奇怪,它比.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;
        }
Run Code Online (Sandbox Code Playgroud)

时间码:

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(); 
        }
Run Code Online (Sandbox Code Playgroud)

结果:

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
Run Code Online (Sandbox Code Playgroud)