【问题标题】:How to convert numbers between hexadecimal and decimal如何在十六进制和十进制之间转换数字
【发布时间】:2010-09-09 14:29:23
【问题描述】:

如何在 C# 中转换十六进制数和十进制数?

【问题讨论】:

    标签: c# hex type-conversion decimal


    【解决方案1】:

    要将十进制转换为十六进制,请...

    string hexValue = decValue.ToString("X");
    

    要将十六进制转换为十进制,请执行以下任一操作...

    int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
    

    int decValue = Convert.ToInt32(hexValue, 16);
    

    【讨论】:

    • 我想了解这行 decValue.ToString("X") 如何将其转换为十六进制。
    • 变量 decValue 是 Int32 类型。 Int32 有一个 ToString() 重载,它可以接受许多格式字符串之一,这些格式字符串指示值将如何表示为字符串。 “X”格式字符串表示十六进制,因此 255.ToString("X") 将返回十六进制字符串“FF”。有关更多信息,请参阅msdn.microsoft.com/en-us/library/dwhawy9k.aspx
    • 好答案。我实际上使用 int.TryParse 而不是 int.Parse 来避免使用烦人的 try catch 块。
    • @ColeJohnson int.Parse 没有选项让您将基数指定为int,就像少数有效的NumberStyles 之一一样。对于基数 16,两者都可以,但作为一般解决方案,最好了解两者的工作原理。
    • 这适用于任何可以表示为整数(包括 Int64)的东西,但不适用于更大的小数或浮点数,例如 20 位数字等。当专门处理更大的数字时,其他一些答案是更正确。互换使用 int 和 decimal 是危险且具有误导性的。
    【解决方案2】:

    十六进制 -> 十进制:

    Convert.ToInt64(hexValue, 16);
    

    十进制 -> 十六进制

    string.format("{0:x}", decValue);
    

    【讨论】:

    • +1 Convert.ToInt64(hexValue, 16); 的好处在于,无论0x 前缀是否存在,它都会进行转换,而其他一些解决方案则不会。
    • @Craig hi,所以我需要根据十六进制值大小进行转换,或者我可以对所有十六进制值应用 ToInt64,会有什么影响吗?
    • Pleeeeeease,当提供来自特定命名空间的东西的解决方案时,请指出它是哪个命名空间!
    • 这仅适用于整数转换人员!!小数会引发错误。
    【解决方案3】:

    看来你可以说

    Convert.ToInt64(value, 16)
    

    从十六进制中获取小数。

    反之亦然:

    otherVar.ToString("X");
    

    【讨论】:

    • 我得到 System.FormatException: The specified format 'x' is invalid
    • 这仅适用于整数。如果要将十进制十六进制转换为十进制或其他方式,则会引发错误。
    【解决方案4】:

    如果您希望在从十六进制数转换为十进制数时获得最佳性能,您可以使用预填充十六进制到十进制值表的方法。

    这是说明该想法的代码。我的performance tests 表明它可以比 Convert.ToInt32(...) 快 20%-40%:

    class TableConvert
      {
          static sbyte[] unhex_table =
          { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
           ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
           ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
           , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1
           ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
           ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
           ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
           ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
          };
    
          public static int Convert(string hexNumber)
          {
              int decValue = unhex_table[(byte)hexNumber[0]];
              for (int i = 1; i < hexNumber.Length; i++)
              {
                  decValue *= 16;
                  decValue += unhex_table[(byte)hexNumber[i]];
              }
              return decValue;
          }
      }
    

    【讨论】:

    • 天才!想知道是否可以让字节编译器在 Convert.ToInt32 中自动使用这种方法?
    • 我看不出有什么原因无法完成。但是,维护数组会消耗额外的内存。
    【解决方案5】:

    From Geekpedia:

    // Store integer 182
    int decValue = 182;
    
    // Convert integer 182 as a hex in a string variable
    string hexValue = decValue.ToString("X");
    
    // Convert the hex string back to the number
    int decAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
    

    【讨论】:

    • 我用这种方法在几分钟内制作了一个小的 dotnet 4.0 应用程序,只需几行代码就可以很好地工作。
    【解决方案6】:
    String stringrep = myintvar.ToString("X");
    
    int num = int.Parse("FF", System.Globalization.NumberStyles.HexNumber);
    

    【讨论】:

    • 这不适用于十进制十六进制值。 System.ArgumentException: '浮点数据类型不支持数字样式 AllowHexSpecifier。'
    【解决方案7】:

    十六进制转十进制

    Convert.ToInt32(number, 16);
    

    十进制到十六进制转换

    int.Parse(number, System.Globalization.NumberStyles.HexNumber)
    

    For more details Check this article

    【讨论】:

    【解决方案8】:

    尝试在 C# 中使用 BigNumber - 表示任意大的有符号整数。

    程序

    using System.Numerics;
    ...
    var bigNumber = BigInteger.Parse("837593454735734579347547357233757342857087879423437472347757234945743");
    Console.WriteLine(bigNumber.ToString("X"));
    

    输出

    4F30DC39A5B10A824134D5B18EEA3707AC854EE565414ED2E498DCFDE1A15DA5FEB6074AE248458435BD417F06F674EB29A2CFECF
    

    可能的例外情况,

    ArgumentNullException - 值为 null。

    FormatException - 值的格式不正确。

    结论

    您可以转换字符串并将值存储在 BigNumber 中,而不受数字大小的限制,除非字符串为空且非字母

    【讨论】:

      【解决方案9】:
          static string chex(byte e)                  // Convert a byte to a string representing that byte in hexadecimal
          {
              string r = "";
              string chars = "0123456789ABCDEF";
              r += chars[e >> 4];
              return r += chars[e &= 0x0F];
          }           // Easy enough...
      
          static byte CRAZY_BYTE(string t, int i)     // Take a byte, if zero return zero, else throw exception (i=0 means false, i>0 means true)
          {
              if (i == 0) return 0;
              throw new Exception(t);
          }
      
          static byte hbyte(string e)                 // Take 2 characters: these are hex chars, convert it to a byte
          {                                           // WARNING: This code will make small children cry. Rated R.
              e = e.ToUpper(); // 
              string msg = "INVALID CHARS";           // The message that will be thrown if the hex str is invalid
      
              byte[] t = new byte[]                   // Gets the 2 characters and puts them in seperate entries in a byte array.
              {                                       // This will throw an exception if (e.Length != 2).
                  (byte)e[CRAZY_BYTE("INVALID LENGTH", e.Length ^ 0x02)], 
                  (byte)e[0x01] 
              };
      
              for (byte i = 0x00; i < 0x02; i++)      // Convert those [ascii] characters to [hexadecimal] characters. Error out if either character is invalid.
              {
                  t[i] -= (byte)((t[i] >= 0x30) ? 0x30 : CRAZY_BYTE(msg, 0x01));                                  // Check for 0-9
                  t[i] -= (byte)((!(t[i] < 0x0A)) ? (t[i] >= 0x11 ? 0x07 : CRAZY_BYTE(msg, 0x01)) : 0x00);        // Check for A-F
              }           
      
              return t[0x01] |= t[0x00] <<= 0x04;     // The moment of truth.
          }
      

      【讨论】:

        【解决方案10】:

        这不是最简单的方法,但此源代码使您能够正确任何类型的八进制数,即 23.214、23 和 0.512 等。希望这会对你有所帮助..

            public string octal_to_decimal(string m_value)
            {
                double i, j, x = 0;
                Int64 main_value;
                int k = 0;
                bool pw = true, ch;
                int position_pt = m_value.IndexOf(".");
                if (position_pt == -1)
                {
                    main_value = Convert.ToInt64(m_value);
                    ch = false;
                }
                else
                {
                    main_value = Convert.ToInt64(m_value.Remove(position_pt, m_value.Length - position_pt));
                    ch = true;
                }
        
                while (k <= 1)
                {
                    do
                    {
                        i = main_value % 10;                                        // Return Remainder
                        i = i * Convert.ToDouble(Math.Pow(8, x));                   // calculate power
                        if (pw)
                            x++;
                        else
                            x--;
                        o_to_d = o_to_d + i;                                        // Saving Required calculated value in main variable
                        main_value = main_value / 10;                               // Dividing the main value 
                    }
                    while (main_value >= 1);
                    if (ch)
                    {
                        k++;
                        main_value = Convert.ToInt64(Reversestring(m_value.Remove(0, position_pt + 1)));
                    }
                    else
                        k = 2;
                    pw = false;
                    x = -1;
                }
                return (Convert.ToString(o_to_d));
            }    
        

        【讨论】:

        • 欢迎使用 stackoverflow。你能解释一下你的代码吗(我可能只是一个简短的句子)。谢谢!
        【解决方案11】:

        如果它是一个超出正常整数容量的非常大的十六进制字符串:

        对于 .NET 3.5,我们可以使用 BouncyCastle 的 BigInteger 类:

        String hex = "68c7b05d0000000002f8";
        // results in "494809724602834812404472"
        String decimal = new Org.BouncyCastle.Math.BigInteger(hex, 16).ToString();
        

        .NET 4.0 有 BigInteger 类。

        【讨论】:

          【解决方案12】:

          这个对我有用:

          public static decimal HexToDec(string hex)
          {
            if (hex.Length % 2 == 1)
              hex = "0" + hex;
            byte[] raw = new byte[hex.Length / 2];
            decimal d = 0;
              for (int i = 0; i < raw.Length; i++)
              {
                raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
                d += Math.Pow(256, (raw.Length - 1 - i)) * raw[i];
              }
              return d.ToString();
            return d;
          }
          

          【讨论】:

            【解决方案13】:

            我的版本是我认为更容易理解的,因为我的 C# 知识不是那么高。 我正在使用这个算法:http://easyguyevo.hubpages.com/hub/Convert-Hex-to-Decimal(示例 2)

            using System;
            using System.Collections.Generic;
            
            static class Tool
            {
                public static string DecToHex(int x)
                {
                    string result = "";
            
                    while (x != 0)
                    {
                        if ((x % 16) < 10)
                            result = x % 16 + result;
                        else
                        {
                            string temp = "";
            
                            switch (x % 16)
                            {
                                case 10: temp = "A"; break;
                                case 11: temp = "B"; break;
                                case 12: temp = "C"; break;
                                case 13: temp = "D"; break;
                                case 14: temp = "E"; break;
                                case 15: temp = "F"; break;
                            }
            
                            result = temp + result;
                        }
            
                        x /= 16;
                    }
            
                    return result;
                }
            
                public static int HexToDec(string x)
                {
                    int result = 0;
                    int count = x.Length - 1;
                    for (int i = 0; i < x.Length; i++)
                    {
                        int temp = 0;
                        switch (x[i])
                        {
                            case 'A': temp = 10; break;
                            case 'B': temp = 11; break;
                            case 'C': temp = 12; break;
                            case 'D': temp = 13; break;
                            case 'E': temp = 14; break;
                            case 'F': temp = 15; break;
                            default: temp = -48 + (int)x[i]; break; // -48 because of ASCII
                        }
            
                        result += temp * (int)(Math.Pow(16, count));
                        count--;
                    }
            
                    return result;
                }
            }
            
            class Program
            {
                static void Main(string[] args)
                {
                    Console.Write("Enter Decimal value: ");
                    int decNum = int.Parse(Console.ReadLine());
            
                    Console.WriteLine("Dec {0} is hex {1}", decNum, Tool.DecToHex(decNum));
            
                    Console.Write("\nEnter Hexadecimal value: ");
                    string hexNum = Console.ReadLine().ToUpper();
            
                    Console.WriteLine("Hex {0} is dec {1}", hexNum, Tool.HexToDec(hexNum));
            
                    Console.ReadKey();
                }
            }
            

            【讨论】:

              【解决方案14】:

              二进制转十六进制

              Convert.ToString(Convert.ToUInt32(binary1, 2), 16).ToUpper()
              

              【讨论】:

                【解决方案15】:

                您可以使用此代码并可能设置十六进制长度和部分:

                const int decimal_places = 4;
                const int int_places = 4;
                static readonly string decimal_places_format = $"X{decimal_places}";
                static readonly string int_places_format = $"X{int_places}";
                
                public static string DecimaltoHex(decimal number)
                {
                    var n = (int)Math.Truncate(number);
                    var f = (int)Math.Truncate((number - n) * ((decimal)Math.Pow(10, decimal_places)));
                    return $"{string.Format($"{{0:{int_places_format}}}", n)}{string.Format($"{{0:{decimal_places_format}}}", f)}";
                }
                
                public static decimal HextoDecimal(string number)
                {
                    var n = number.Substring(0, number.Length - decimal_places);
                    var f = number.Substring(number.Length - decimal_places);
                    return decimal.Parse($"{int.Parse(n, System.Globalization.NumberStyles.HexNumber)}.{int.Parse(f, System.Globalization.NumberStyles.HexNumber)}");
                }
                

                【讨论】:

                  【解决方案16】:

                  十进制 - 十六进制

                          var decValue = int.Parse(Console.ReadLine());
                          string hex = string.Format("{0:x}", decValue);
                          Console.WriteLine(hex);
                  

                  Hexa - 十进制(使用命名空间:使用 System.Globalization;)

                          var hexval = Console.ReadLine();
                          int decValue = int.Parse(hexval, NumberStyles.HexNumber);
                          Console.WriteLine(decValue);
                  

                  【讨论】:

                    【解决方案17】:

                    一种将字节数组转换为十六进制表示的扩展方法。这用前导零填充每个字节。

                        /// <summary>
                        /// Turns the byte array into its Hex representation.
                        /// </summary>
                        public static string ToHex(this byte[] y)
                        {
                            StringBuilder sb = new StringBuilder();
                            foreach (byte b in y)
                            {
                                sb.Append(b.ToString("X").PadLeft(2, "0"[0]));
                            }
                            return sb.ToString();
                        }
                    

                    【讨论】:

                      【解决方案18】:

                      这是我的功能:

                      using System;
                      using System.Collections.Generic;
                      class HexadecimalToDecimal
                      {
                          static Dictionary<char, int> hexdecval = new Dictionary<char, int>{
                              {'0', 0},
                              {'1', 1},
                              {'2', 2},
                              {'3', 3},
                              {'4', 4},
                              {'5', 5},
                              {'6', 6},
                              {'7', 7},
                              {'8', 8},
                              {'9', 9},
                              {'a', 10},
                              {'b', 11},
                              {'c', 12},
                              {'d', 13},
                              {'e', 14},
                              {'f', 15},
                          };
                      
                          static decimal HexToDec(string hex)
                          {
                              decimal result = 0;
                              hex = hex.ToLower();
                      
                              for (int i = 0; i < hex.Length; i++)
                              {
                                  char valAt = hex[hex.Length - 1 - i];
                                  result += hexdecval[valAt] * (int)Math.Pow(16, i);
                              }
                      
                              return result;
                          }
                      
                          static void Main()
                          {
                      
                              Console.WriteLine("Enter Hexadecimal value");
                              string hex = Console.ReadLine().Trim();
                      
                              //string hex = "29A";
                              Console.WriteLine("Hex {0} is dec {1}", hex, HexToDec(hex));
                      
                              Console.ReadKey();
                          }
                      }
                      

                      【讨论】:

                      • 这可能是 Convert 扩展方法的一个很好的候选,这样人们就可以写:int hexa = Convert.ToHexadecimal(11); =)
                      【解决方案19】:

                      我的解决方案有点像返璞归真,但它无需使用任何内置函数即可在数字系统之间进行转换。

                          public static string DecToHex(long a)
                          {
                              int n = 1;
                              long b = a;
                              while (b > 15)
                              {
                                  b /= 16;
                                  n++;
                              }
                              string[] t = new string[n];
                              int i = 0, j = n - 1;
                              do
                              {
                                       if (a % 16 == 10) t[i] = "A";
                                  else if (a % 16 == 11) t[i] = "B";
                                  else if (a % 16 == 12) t[i] = "C";
                                  else if (a % 16 == 13) t[i] = "D";
                                  else if (a % 16 == 14) t[i] = "E";
                                  else if (a % 16 == 15) t[i] = "F";
                                  else t[i] = (a % 16).ToString();
                                  a /= 16;
                                  i++;
                              }
                              while ((a * 16) > 15);
                              string[] r = new string[n];
                              for (i = 0; i < n; i++)
                              {
                                  r[i] = t[j];
                                  j--;
                              }
                              string res = string.Concat(r);
                              return res;
                          }
                      

                      【讨论】:

                        猜你喜欢
                        • 2018-01-16
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 2019-07-26
                        • 2014-03-19
                        相关资源
                        最近更新 更多