首页 文章

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

提问于
浏览
394

我该如何转换以下内容?

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

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

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

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

10 回答

  • 52

    至十六进制:

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

    到int:

    int intValue = int.Parse(hex, System.Globalization.NumberStyles.HexNumber)
    
  • 15
    // 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

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

  • -1

    NET FRAMEWORK

    非常好的解释和很少的编程线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#

    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;
            }
        }
    
  • 18

    int到hex:

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

    十六进制到int:

    int b = 0xB76; Console.WriteLine(b)中;

  • 740

    使用:

    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) .

  • 6
    string HexFromID(int ID)
    {
        return ID.ToString("X");
    }
    
    int IDFromHex(string HexID)
    {
        return int.Parse(HexID, System.Globalization.NumberStyles.HexNumber);
    }
    

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

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

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

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

  • -5

    在找到这个答案之前,我创建了自己的解决方案,用于将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
    
  • 96
    int valInt = 12;
    Console.WriteLine(valInt.ToString("X"));  // C  ~ possibly single-digit output 
    Console.WriteLine(valInt.ToString("X2")); // 0C ~ always double-digit output
    
  • 14

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

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

相关问题