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

时间:2009-07-16 20:05:01

标签: c# hex type-conversion

如何转换以下内容?

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

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

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

在C#中有一种简单的方法吗?

12 个答案:

答案 0 :(得分:787)

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

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

答案 1 :(得分:101)

使用:

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

有关更多信息和示例,请参阅 How to: Convert Between Hexadecimal Strings and Numeric Types (C# Programming Guide)

答案 2 :(得分:52)

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

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

答案 3 :(得分:18)

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(等长)。

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

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

答案 4 :(得分:16)

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

答案 5 :(得分:14)

To Hex:

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

到int:

int intValue = int.Parse(hex, System.Globalization.NumberStyles.HexNumber)

答案 6 :(得分:6)

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

时间码:

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

答案 7 :(得分:1)

时髦的迟来的回应,但你考虑过某种Integer缩短的实施吗?如果唯一的目标是尽可能缩短用户ID,我有兴趣知道是否还有其他明显的理由要求您特别要求十六进制转换 - 除非我当然错过了它。是否明确且已知(如果需要)用户ID实际上是实际值的十六进制表示?

答案 8 :(得分:0)

网络框架

  

解释得非常好,编程行很少   好的工作

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

答案 9 :(得分:0)

我无法发表评论,但有些人误解为intValue.ToString("X2")将“指定位数”或产生“始终两位数输出”。 这是不正确的,2指定了最小个数字。因此,如果您具有不透明的黑色ARGB颜色,则该方法将产生FF000000而不是00

答案 10 :(得分:0)

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

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

答案 11 :(得分:-5)

int to hex:

  

int a = 72;

     

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

hex to int:

  

int b = 0xB76;

     

Console.WriteLine(B);

相关问题