<p>How do you convert between hexadecimal numbers and decimal numbers in C#?</p>

[{'answer_id': 74183, 'author': 'Sklivvz', 'author_id': 7028, 'author_profile': 'https://Stackoverflow.com/users/7028', 'pm_score': 2, 'selected': False, 'text': '<pre><code>String stringrep = myintvar.ToString("X");\n\nint num = int.Parse("FF", System.Globalization.NumberStyles.HexNumber);\n</code></pre>\n'}, {'answer_id': 74185, 'author': 'Jesper Blad Jensen', 'author_id': 11559, 'author_profile': 'https://Stackoverflow.com/users/11559', 'pm_score': 5, 'selected': False, 'text': '<p>It looks like you can say</p>\n\n<pre><code>Convert.ToInt64(value, 16)\n</code></pre>\n\n<p>to get the decimal from hexdecimal.</p>\n\n<p>The other way around is:</p>\n\n<pre><code>otherVar.ToString("X");\n</code></pre>\n'}, {'answer_id': 74191, 'author': 'Rob', 'author_id': 12413, 'author_profile': 'https://Stackoverflow.com/users/12413', 'pm_score': 4, 'selected': False, 'text': '<p><a href="https://web.archive.org/web/20081231062758/http://www.geekpedia.com/KB8_How-do-I-convert-from-decimal-to-hex-and-hex-to-decimal.html" rel="noreferrer">From Geekpedia</a>:</p>\n\n<pre><code>// Store integer 182\nint decValue = 182;\n\n// Convert integer 182 as a hex in a string variable\nstring hexValue = decValue.ToString("X");\n\n// Convert the hex string back to the number\nint decAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);\n</code></pre>\n'}, {'answer_id': 74198, 'author': 'Jonathan Rupp', 'author_id': 12502, 'author_profile': 'https://Stackoverflow.com/users/12502', 'pm_score': 6, 'selected': False, 'text': '<p>Hex -&gt; decimal:</p>\n<pre><code>Convert.ToInt64(hexString, 16);\n</code></pre>\n<p>Decimal -&gt; Hex</p>\n<pre><code>string.Format(&quot;{0:x}&quot;, intValue);\n</code></pre>\n'}, {'answer_id': 74223, 'author': 'Andy McCluggage', 'author_id': 3362, 'author_profile': 'https://Stackoverflow.com/users/3362', 'pm_score': 9, 'selected': True, 'text': '<p>To convert from decimal to hex do...</p>\n\n<pre><code>string hexValue = decValue.ToString("X");\n</code></pre>\n\n<p>To convert from hex to decimal do either...</p>\n\n<pre><code>int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);\n</code></pre>\n\n<p>or  </p>\n\n<pre><code>int decValue = Convert.ToInt32(hexValue, 16);\n</code></pre>\n'}, {'answer_id': 2484244, 'author': 'Ecstatic Coder', 'author_id': 298120, 'author_profile': 'https://Stackoverflow.com/users/298120', 'pm_score': 1, 'selected': False, 'text': '<pre><code>    static string chex(byte e)                  // Convert a byte to a string representing that byte in hexadecimal\n    {\n        string r = "";\n        string chars = "0123456789ABCDEF";\n        r += chars[e &gt;&gt; 4];\n        return r += chars[e &amp;= 0x0F];\n    }           // Easy enough...\n\n    static byte CRAZY_BYTE(string t, int i)     // Take a byte, if zero return zero, else throw exception (i=0 means false, i&gt;0 means true)\n    {\n        if (i == 0) return 0;\n        throw new Exception(t);\n    }\n\n    static byte hbyte(string e)                 // Take 2 characters: these are hex chars, convert it to a byte\n    {                                           // WARNING: This code will make small children cry. Rated R.\n        e = e.ToUpper(); // \n        string msg = "INVALID CHARS";           // The message that will be thrown if the hex str is invalid\n\n        byte[] t = new byte[]                   // Gets the 2 characters and puts them in seperate entries in a byte array.\n        {                                       // This will throw an exception if (e.Length != 2).\n            (byte)e[CRAZY_BYTE("INVALID LENGTH", e.Length ^ 0x02)], \n            (byte)e[0x01] \n        };\n\n        for (byte i = 0x00; i &lt; 0x02; i++)      // Convert those [ascii] characters to [hexadecimal] characters. Error out if either character is invalid.\n        {\n            t[i] -= (byte)((t[i] &gt;= 0x30) ? 0x30 : CRAZY_BYTE(msg, 0x01));                                  // Check for 0-9\n            t[i] -= (byte)((!(t[i] &lt; 0x0A)) ? (t[i] &gt;= 0x11 ? 0x07 : CRAZY_BYTE(msg, 0x01)) : 0x00);        // Check for A-F\n        }           \n\n        return t[0x01] |= t[0x00] &lt;&lt;= 0x04;     // The moment of truth.\n    }\n</code></pre>\n'}, {'answer_id': 4474966, 'author': 'Omair', 'author_id': 546562, 'author_profile': 'https://Stackoverflow.com/users/546562', 'pm_score': 1, 'selected': False, 'text': '<p>This is not really easiest way but this source code enable you to right any types of octal number i.e 23.214, 23 and 0.512 and so on. Hope this will help you..</p>\n\n<pre><code>    public string octal_to_decimal(string m_value)\n    {\n        double i, j, x = 0;\n        Int64 main_value;\n        int k = 0;\n        bool pw = true, ch;\n        int position_pt = m_value.IndexOf(".");\n        if (position_pt == -1)\n        {\n            main_value = Convert.ToInt64(m_value);\n            ch = false;\n        }\n        else\n        {\n            main_value = Convert.ToInt64(m_value.Remove(position_pt, m_value.Length - position_pt));\n            ch = true;\n        }\n\n        while (k &lt;= 1)\n        {\n            do\n            {\n                i = main_value % 10;                                        // Return Remainder\n                i = i * Convert.ToDouble(Math.Pow(8, x));                   // calculate power\n                if (pw)\n                    x++;\n                else\n                    x--;\n                o_to_d = o_to_d + i;                                        // Saving Required calculated value in main variable\n                main_value = main_value / 10;                               // Dividing the main value \n            }\n            while (main_value &gt;= 1);\n            if (ch)\n            {\n                k++;\n                main_value = Convert.ToInt64(Reversestring(m_value.Remove(0, position_pt + 1)));\n            }\n            else\n                k = 2;\n            pw = false;\n            x = -1;\n        }\n        return (Convert.ToString(o_to_d));\n    }    \n</code></pre>\n'}, {'answer_id': 6205484, 'author': 'msanjay', 'author_id': 392985, 'author_profile': 'https://Stackoverflow.com/users/392985', 'pm_score': 2, 'selected': False, 'text': '<p>If it\'s a really big hex string beyond the capacity of the normal integer:</p>\n\n<p>For .NET 3.5, we can use BouncyCastle\'s BigInteger class:</p>\n\n<pre><code>String hex = "68c7b05d0000000002f8";\n// results in "494809724602834812404472"\nString decimal = new Org.BouncyCastle.Math.BigInteger(hex, 16).ToString();\n</code></pre>\n\n<p>.NET 4.0 has the <a href="http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx" rel="nofollow">BigInteger</a> class.</p>\n'}, {'answer_id': 6666767, 'author': 'Luke Puplett', 'author_id': 107783, 'author_profile': 'https://Stackoverflow.com/users/107783', 'pm_score': -1, 'selected': False, 'text': '<p>An extension method for converting a byte array into a hex representation. This pads each byte with leading zeros.</p>\n\n<pre><code>    /// &lt;summary&gt;\n    /// Turns the byte array into its Hex representation.\n    /// &lt;/summary&gt;\n    public static string ToHex(this byte[] y)\n    {\n        StringBuilder sb = new StringBuilder();\n        foreach (byte b in y)\n        {\n            sb.Append(b.ToString("X").PadLeft(2, "0"[0]));\n        }\n        return sb.ToString();\n    }\n</code></pre>\n'}, {'answer_id': 9126750, 'author': 'Vadym Stetsiak', 'author_id': 6952, 'author_profile': 'https://Stackoverflow.com/users/6952', 'pm_score': 4, 'selected': False, 'text': '<p>If you want maximum performance when doing conversion from hex to decimal number, you can use the approach with pre-populated table of hex-to-decimal values.</p>\n\n<p>Here is the code that illustrates that idea. My <a href="http://vadmyst.blogspot.com/2012/02/fast-convertion-of-hex-string-into.html" rel="noreferrer">performance tests</a> showed that it can be 20%-40% faster than Convert.ToInt32(...):</p>\n\n<pre><code>class TableConvert\n  {\n      static sbyte[] unhex_table =\n      { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n       ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n       ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n       , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1\n       ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1\n       ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n       ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1\n       ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n      };\n\n      public static int Convert(string hexNumber)\n      {\n          int decValue = unhex_table[(byte)hexNumber[0]];\n          for (int i = 1; i &lt; hexNumber.Length; i++)\n          {\n              decValue *= 16;\n              decValue += unhex_table[(byte)hexNumber[i]];\n          }\n          return decValue;\n      }\n  }\n</code></pre>\n'}, {'answer_id': 21079586, 'author': 'Chris Panayotoff', 'author_id': 1584898, 'author_profile': 'https://Stackoverflow.com/users/1584898', 'pm_score': -1, 'selected': False, 'text': '<p>Here is my function:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nclass HexadecimalToDecimal\n{\n    static Dictionary&lt;char, int&gt; hexdecval = new Dictionary&lt;char, int&gt;{\n        {\'0\', 0},\n        {\'1\', 1},\n        {\'2\', 2},\n        {\'3\', 3},\n        {\'4\', 4},\n        {\'5\', 5},\n        {\'6\', 6},\n        {\'7\', 7},\n        {\'8\', 8},\n        {\'9\', 9},\n        {\'a\', 10},\n        {\'b\', 11},\n        {\'c\', 12},\n        {\'d\', 13},\n        {\'e\', 14},\n        {\'f\', 15},\n    };\n\n    static decimal HexToDec(string hex)\n    {\n        decimal result = 0;\n        hex = hex.ToLower();\n\n        for (int i = 0; i &lt; hex.Length; i++)\n        {\n            char valAt = hex[hex.Length - 1 - i];\n            result += hexdecval[valAt] * (int)Math.Pow(16, i);\n        }\n\n        return result;\n    }\n\n    static void Main()\n    {\n\n        Console.WriteLine("Enter Hexadecimal value");\n        string hex = Console.ReadLine().Trim();\n\n        //string hex = "29A";\n        Console.WriteLine("Hex {0} is dec {1}", hex, HexToDec(hex));\n\n        Console.ReadKey();\n    }\n}\n</code></pre>\n'}, {'answer_id': 28408141, 'author': 'Mihók Balázs', 'author_id': 4545945, 'author_profile': 'https://Stackoverflow.com/users/4545945', 'pm_score': 0, 'selected': False, 'text': '<p>My version is I think a little more understandable because my C# knowledge is not so high.\nI\'m using this algorithm: <a href="http://easyguyevo.hubpages.com/hub/Convert-Hex-to-Decimal" rel="nofollow">http://easyguyevo.hubpages.com/hub/Convert-Hex-to-Decimal</a> (The Example 2)</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\n\nstatic class Tool\n{\n    public static string DecToHex(int x)\n    {\n        string result = "";\n\n        while (x != 0)\n        {\n            if ((x % 16) &lt; 10)\n                result = x % 16 + result;\n            else\n            {\n                string temp = "";\n\n                switch (x % 16)\n                {\n                    case 10: temp = "A"; break;\n                    case 11: temp = "B"; break;\n                    case 12: temp = "C"; break;\n                    case 13: temp = "D"; break;\n                    case 14: temp = "E"; break;\n                    case 15: temp = "F"; break;\n                }\n\n                result = temp + result;\n            }\n\n            x /= 16;\n        }\n\n        return result;\n    }\n\n    public static int HexToDec(string x)\n    {\n        int result = 0;\n        int count = x.Length - 1;\n        for (int i = 0; i &lt; x.Length; i++)\n        {\n            int temp = 0;\n            switch (x[i])\n            {\n                case \'A\': temp = 10; break;\n                case \'B\': temp = 11; break;\n                case \'C\': temp = 12; break;\n                case \'D\': temp = 13; break;\n                case \'E\': temp = 14; break;\n                case \'F\': temp = 15; break;\n                default: temp = -48 + (int)x[i]; break; // -48 because of ASCII\n            }\n\n            result += temp * (int)(Math.Pow(16, count));\n            count--;\n        }\n\n        return result;\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        Console.Write("Enter Decimal value: ");\n        int decNum = int.Parse(Console.ReadLine());\n\n        Console.WriteLine("Dec {0} is hex {1}", decNum, Tool.DecToHex(decNum));\n\n        Console.Write("\\nEnter Hexadecimal value: ");\n        string hexNum = Console.ReadLine().ToUpper();\n\n        Console.WriteLine("Hex {0} is dec {1}", hexNum, Tool.HexToDec(hexNum));\n\n        Console.ReadKey();\n    }\n}\n</code></pre>\n'}, {'answer_id': 29939746, 'author': 'Jewel', 'author_id': 4845704, 'author_profile': 'https://Stackoverflow.com/users/4845704', 'pm_score': 0, 'selected': False, 'text': '<p>Convert binary to Hex</p>\n\n<pre><code>Convert.ToString(Convert.ToUInt32(binary1, 2), 16).ToUpper()\n</code></pre>\n'}, {'answer_id': 44120599, 'author': 'user7925882', 'author_id': 7925882, 'author_profile': 'https://Stackoverflow.com/users/7925882', 'pm_score': 2, 'selected': False, 'text': '<p>Hex to Decimal Conversion</p>\n\n<pre><code>Convert.ToInt32(number, 16);\n</code></pre>\n\n<p>Decimal to Hex Conversion</p>\n\n<pre><code>int.Parse(number, System.Globalization.NumberStyles.HexNumber)\n</code></pre>\n\n<p><a href="http://kodecenter.com/article?id=f3ed25f1-2563-4323-9f43-c4fbbc9c372f" rel="nofollow noreferrer">For more details Check this article</a></p>\n'}, {'answer_id': 49569835, 'author': 'Aravin', 'author_id': 3058254, 'author_profile': 'https://Stackoverflow.com/users/3058254', 'pm_score': 2, 'selected': False, 'text': '<p>Try using BigNumber in C# - Represents an arbitrarily large signed integer.</p>\n\n<h3>Program</h3>\n\n<pre><code>using System.Numerics;\n...\nvar bigNumber = BigInteger.Parse("837593454735734579347547357233757342857087879423437472347757234945743");\nConsole.WriteLine(bigNumber.ToString("X"));\n</code></pre>\n\n<h3>Output</h3>\n\n<pre><code>4F30DC39A5B10A824134D5B18EEA3707AC854EE565414ED2E498DCFDE1A15DA5FEB6074AE248458435BD417F06F674EB29A2CFECF\n</code></pre>\n\n<h3>Possible Exceptions,</h3>\n\n<p>ArgumentNullException - value is null.</p>\n\n<p>FormatException - value is not in the correct format.</p>\n\n<h3>Conclusion</h3>\n\n<p>You can convert string and store a value in BigNumber without constraints about the size of the number unless the string is empty and non-analphabets</p>\n'}, {'answer_id': 54082994, 'author': 'Krisztián Molnár', 'author_id': 10881471, 'author_profile': 'https://Stackoverflow.com/users/10881471', 'pm_score': -1, 'selected': False, 'text': '<p>My solution is a bit like back to basics, but it works without using any built-in functions to convert between number systems.</p>\n\n<pre><code>    public static string DecToHex(long a)\n    {\n        int n = 1;\n        long b = a;\n        while (b &gt; 15)\n        {\n            b /= 16;\n            n++;\n        }\n        string[] t = new string[n];\n        int i = 0, j = n - 1;\n        do\n        {\n                 if (a % 16 == 10) t[i] = "A";\n            else if (a % 16 == 11) t[i] = "B";\n            else if (a % 16 == 12) t[i] = "C";\n            else if (a % 16 == 13) t[i] = "D";\n            else if (a % 16 == 14) t[i] = "E";\n            else if (a % 16 == 15) t[i] = "F";\n            else t[i] = (a % 16).ToString();\n            a /= 16;\n            i++;\n        }\n        while ((a * 16) &gt; 15);\n        string[] r = new string[n];\n        for (i = 0; i &lt; n; i++)\n        {\n            r[i] = t[j];\n            j--;\n        }\n        string res = string.Concat(r);\n        return res;\n    }\n</code></pre>\n'}, {'answer_id': 67015650, 'author': 'MohsenB', 'author_id': 1358148, 'author_profile': 'https://Stackoverflow.com/users/1358148', 'pm_score': 0, 'selected': False, 'text': "<p>You can use this code and possible set Hex length and part's:<br></p>\n<pre><code>const int decimal_places = 4;\nconst int int_places = 4;\nstatic readonly string decimal_places_format = $&quot;X{decimal_places}&quot;;\nstatic readonly string int_places_format = $&quot;X{int_places}&quot;;\n\npublic static string DecimaltoHex(decimal number)\n{\n    var n = (int)Math.Truncate(number);\n    var f = (int)Math.Truncate((number - n) * ((decimal)Math.Pow(10, decimal_places)));\n    return $&quot;{string.Format($&quot;{{0:{int_places_format}}}&quot;, n)}{string.Format($&quot;{{0:{decimal_places_format}}}&quot;, f)}&quot;;\n}\n\npublic static decimal HextoDecimal(string number)\n{\n    var n = number.Substring(0, number.Length - decimal_places);\n    var f = number.Substring(number.Length - decimal_places);\n    return decimal.Parse($&quot;{int.Parse(n, System.Globalization.NumberStyles.HexNumber)}.{int.Parse(f, System.Globalization.NumberStyles.HexNumber)}&quot;);\n}\n</code></pre>\n"}, {'answer_id': 67652913, 'author': 'Dejan Dozet', 'author_id': 4541566, 'author_profile': 'https://Stackoverflow.com/users/4541566', 'pm_score': 1, 'selected': False, 'text': '<p>This one worked for me:</p>\n<pre><code>public static decimal HexToDec(string hex)\n{\n  if (hex.Length % 2 == 1)\n    hex = &quot;0&quot; + hex;\n  byte[] raw = new byte[hex.Length / 2];\n  decimal d = 0;\n    for (int i = 0; i &lt; raw.Length; i++)\n    {\n      raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);\n      d += Math.Pow(256, (raw.Length - 1 - i)) * raw[i];\n    }\n    return d.ToString();\n  return d;\n}\n</code></pre>\n'}, {'answer_id': 68256392, 'author': 'Rakibul', 'author_id': 12944359, 'author_profile': 'https://Stackoverflow.com/users/12944359', 'pm_score': 1, 'selected': False, 'text': '<p>Decimal - Hexa</p>\n<pre><code>        var decValue = int.Parse(Console.ReadLine());\n        string hex = string.Format(&quot;{0:x}&quot;, decValue);\n        Console.WriteLine(hex);\n</code></pre>\n<p>Hexa - Decimal (use namespace: using System.Globalization;)</p>\n<pre><code>        var hexval = Console.ReadLine();\n        int decValue = int.Parse(hexval, NumberStyles.HexNumber);\n        Console.WriteLine(decValue);\n</code></pre>\n'}, {'answer_id': 71229254, 'author': 'Marco Antonio', 'author_id': 6907130, 'author_profile': 'https://Stackoverflow.com/users/6907130', 'pm_score': 1, 'selected': False, 'text': '<p><strong>FOUR C# native ways to convert Hex to Dec and back:</strong></p>\n<pre><code>using System;\n\nnamespace Hexadecimal_and_Decimal\n{\n  internal class Program\n  {\n    private static void Main(string[] args)\n    {\n      string hex = &quot;4DEAD&quot;;\n      int dec;\n\n      // hex to dec:\n      dec = int.Parse(hex, System.Globalization.NumberStyles.HexNumber);\n      // or:\n      dec = Convert.ToInt32(hex, 16);\n\n      // dec to hex:\n      hex = dec.ToString(&quot;X&quot;); // lowcase: x, uppercase: X\n      // or:\n      hex = string.Format(&quot;{0:X}&quot;, dec); // lowcase: x, uppercase: X\n\n      Console.WriteLine(&quot;Hexadecimal number: &quot; + hex);\n      Console.WriteLine(&quot;Decimal number: &quot; + dec);\n    }\n  }\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/74148', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3362/']