<p>How do you convert decimal values to their hexadecimal equivalent in JavaScript?</p>

[{'answer_id': 57805, 'author': 'Prestaul', 'author_id': 5628, 'author_profile': 'https://Stackoverflow.com/users/5628', 'pm_score': 13, 'selected': True, 'text': '<p>Convert a number to a hexadecimal string with:</p>\n<pre><code>hexString = yourNumber.toString(16);\n</code></pre>\n<p>And reverse the process with:</p>\n<pre><code>yourNumber = parseInt(hexString, 16);\n</code></pre>\n'}, {'answer_id': 57807, 'author': 'Luke Smith', 'author_id': 5556, 'author_profile': 'https://Stackoverflow.com/users/5556', 'pm_score': 7, 'selected': False, 'text': '<p>The code below will convert the decimal value d to hexadecimal. It also allows you to add padding to the hexadecimal result. So 0 will become 00 by default.</p>\n\n<pre><code>function decimalToHex(d, padding) {\n    var hex = Number(d).toString(16);\n    padding = typeof (padding) === "undefined" || padding === null ? padding = 2 : padding;\n\n    while (hex.length &lt; padding) {\n        hex = "0" + hex;\n    }\n\n    return hex;\n}\n</code></pre>\n'}, {'answer_id': 57814, 'author': 'Danny Wilson', 'author_id': 5364, 'author_profile': 'https://Stackoverflow.com/users/5364', 'pm_score': 4, 'selected': False, 'text': '<pre><code>var number = 3200;\nvar hexString = number.toString(16);\n</code></pre>\n\n<p>The 16 is the radix and there are 16 values in a hexadecimal number :-)</p>\n'}, {'answer_id': 697841, 'author': 'Tod', 'author_id': 16679, 'author_profile': 'https://Stackoverflow.com/users/16679', 'pm_score': 7, 'selected': False, 'text': '<p>If you need to handle things like bit fields or 32-bit colors, then you need to deal with signed numbers. The JavaScript function <code>toString(16)</code> will return a negative hexadecimal number which is usually not what you want. This function does some crazy addition to make it a positive number.</p>\n\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>function decimalToHexString(number)\r\n{\r\n  if (number &lt; 0)\r\n  {\r\n    number = 0xFFFFFFFF + number + 1;\r\n  }\r\n\r\n  return number.toString(16).toUpperCase();\r\n}\r\n\r\nconsole.log(decimalToHexString(27));\r\nconsole.log(decimalToHexString(48.6));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 930315, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<pre><code>function dec2hex(i)\n{\n  var result = "0000";\n  if      (i &gt;= 0    &amp;&amp; i &lt;= 15)    { result = "000" + i.toString(16); }\n  else if (i &gt;= 16   &amp;&amp; i &lt;= 255)   { result = "00"  + i.toString(16); }\n  else if (i &gt;= 256  &amp;&amp; i &lt;= 4095)  { result = "0"   + i.toString(16); }\n  else if (i &gt;= 4096 &amp;&amp; i &lt;= 65535) { result =         i.toString(16); }\n  return result\n}\n</code></pre>\n'}, {'answer_id': 1446578, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>AFAIK <a href="https://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript/57807#57807">comment 57807</a> is wrong and should be something like:\n<strong>var hex = Number(d).toString(16);</strong>\ninstead of\n<strong>var hex = parseInt(d, 16);</strong></p>\n\n<pre><code>function decimalToHex(d, padding) {\n    var hex = Number(d).toString(16);\n    padding = typeof (padding) === "undefined" || padding === null ? padding = 2 : padding;\n\n    while (hex.length &lt; padding) {\n        hex = "0" + hex;\n    }\n\n    return hex;\n}\n</code></pre>\n'}, {'answer_id': 3689638, 'author': 'mystifeid', 'author_id': 444910, 'author_profile': 'https://Stackoverflow.com/users/444910', 'pm_score': 4, 'selected': False, 'text': '<p>Without the loop:</p>\n\n<pre><code>function decimalToHex(d) {\n  var hex = Number(d).toString(16);\n  hex = "000000".substr(0, 6 - hex.length) + hex;\n  return hex;\n}\n\n// Or "#000000".substr(0, 7 - hex.length) + hex;\n// Or whatever\n// *Thanks to MSDN\n</code></pre>\n\n<p>Also isn\'t it better not to use loop tests that have to be evaluated?</p>\n\n<p>For example, instead of:</p>\n\n<pre><code>for (var i = 0; i &lt; hex.length; i++){}\n</code></pre>\n\n<p>have</p>\n\n<pre><code>for (var i = 0, var j = hex.length; i &lt; j; i++){}\n</code></pre>\n'}, {'answer_id': 6680530, 'author': 'Fabio Ferrari', 'author_id': 87648, 'author_profile': 'https://Stackoverflow.com/users/87648', 'pm_score': 5, 'selected': False, 'text': '<p>With padding:</p>\n\n<pre><code>function dec2hex(i) {\n   return (i+0x10000).toString(16).substr(-4).toUpperCase();\n}\n</code></pre>\n'}, {'answer_id': 9034019, 'author': 'Adamarla', 'author_id': 1167359, 'author_profile': 'https://Stackoverflow.com/users/1167359', 'pm_score': 4, 'selected': False, 'text': '<p>Constrained/padded to a set number of characters:</p>\n\n<pre><code>function decimalToHex(decimal, chars) {\n    return (decimal + Math.pow(16, chars)).toString(16).slice(-chars).toUpperCase();\n}\n</code></pre>\n'}, {'answer_id': 11012314, 'author': 'korona', 'author_id': 25731, 'author_profile': 'https://Stackoverflow.com/users/25731', 'pm_score': 3, 'selected': False, 'text': '<p>If you want to convert a number to a hexadecimal representation of an RGBA color value, I\'ve found this to be the most useful combination of several tips from here:</p>\n\n<pre><code>function toHexString(n) {\n    if(n &lt; 0) {\n        n = 0xFFFFFFFF + n + 1;\n    }\n    return "0x" + ("00000000" + n.toString(16).toUpperCase()).substr(-8);\n}\n</code></pre>\n'}, {'answer_id': 12995874, 'author': 'Eliarh', 'author_id': 1762728, 'author_profile': 'https://Stackoverflow.com/users/1762728', 'pm_score': 3, 'selected': False, 'text': "<p>And if the number is negative?</p>\n\n<p>Here is my version.</p>\n\n<pre><code>function hexdec (hex_string) {\n    hex_string=((hex_string.charAt(1)!='X' &amp;&amp; hex_string.charAt(1)!='x')?hex_string='0X'+hex_string : hex_string);\n    hex_string=(hex_string.charAt(2)&lt;8 ? hex_string =hex_string-0x00000000 : hex_string=hex_string-0xFFFFFFFF-1);\n    return parseInt(hex_string, 10);\n}\n</code></pre>\n"}, {'answer_id': 13240395, 'author': 'Baznr', 'author_id': 1801365, 'author_profile': 'https://Stackoverflow.com/users/1801365', 'pm_score': 6, 'selected': False, 'text': '<pre><code>function toHex(d) {\n    return  ("0"+(Number(d).toString(16))).slice(-2).toUpperCase()\n}\n</code></pre>\n'}, {'answer_id': 13397771, 'author': 'Keith Mashinter', 'author_id': 1826649, 'author_profile': 'https://Stackoverflow.com/users/1826649', 'pm_score': 4, 'selected': False, 'text': '<p>Combining some of these good ideas for an RGB-value-to-hexadecimal function (add the <code>#</code> elsewhere for HTML/CSS):</p>\n\n<pre><code>function rgb2hex(r,g,b) {\n    if (g !== undefined)\n        return Number(0x1000000 + r*0x10000 + g*0x100 + b).toString(16).substring(1);\n    else\n        return Number(0x1000000 + r[0]*0x10000 + r[1]*0x100 + r[2]).toString(16).substring(1);\n}\n</code></pre>\n'}, {'answer_id': 13865336, 'author': 'almaz', 'author_id': 460477, 'author_profile': 'https://Stackoverflow.com/users/460477', 'pm_score': 3, 'selected': False, 'text': "<p>I'm doing conversion to hex string in a pretty large loop, so I tried several techniques in order to find the fastest one. My requirements were to have a fixed-length string as a result, and encode negative values properly (-1 => ff..f).</p>\n\n<p>Simple <code>.toString(16)</code> didn't work for me since I needed negative values to be properly encoded. The following code is the quickest I've tested so far on 1-2 byte values (note that <code>symbols</code> defines the number of output symbols you want to get, that is for 4-byte integer it should be equal to 8):</p>\n\n<pre><code>var hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];\nfunction getHexRepresentation(num, symbols) {\n    var result = '';\n    while (symbols--) {\n        result = hex[num &amp; 0xF] + result;\n        num &gt;&gt;= 4;\n    }\n    return result;\n}\n</code></pre>\n\n<p>It performs faster than <code>.toString(16)</code> on 1-2 byte numbers and slower on larger numbers (when <code>symbols</code> >= 6), but still should outperform methods that encode negative values properly.</p>\n"}, {'answer_id': 17023332, 'author': 'R D', 'author_id': 2448914, 'author_profile': 'https://Stackoverflow.com/users/2448914', 'pm_score': 3, 'selected': False, 'text': '<p>As the accepted answer states, the easiest way to convert from decimal to hexadecimal is <code>var hex = dec.toString(16)</code>. However, you may prefer to add a string conversion, as it ensures that string representations like <code>"12".toString(16)</code> work correctly.</p>\n\n<pre><code>// Avoids a hard-to-track-down bug by returning `c` instead of `12`\n(+"12").toString(16);\n</code></pre>\n\n<p>To reverse the process you may also use the solution below, as it is even shorter.</p>\n\n<pre><code>var dec = +("0x" + hex);\n</code></pre>\n\n<p>It seems to be slower in Google Chrome and Firefox, but is significantly faster in Opera. See <a href="http://jsperf.com/hex-to-dec" rel="nofollow noreferrer">http://jsperf.com/hex-to-dec</a>.</p>\n'}, {'answer_id': 17106974, 'author': 'Alberto', 'author_id': 413020, 'author_profile': 'https://Stackoverflow.com/users/413020', 'pm_score': 6, 'selected': False, 'text': '<p>For completeness, if you want the <a href="http://en.wikipedia.org/wiki/Two%27s_complement" rel="noreferrer" title="Two&#39;s complement [Wikipedia]">two\'s-complement</a> hexadecimal representation of a negative number, you can use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#%3E%3E%3E_%28Zero-fill_right_shift%29" rel="noreferrer" title="Zero-fill right shift [MDN]">zero-fill-right shift <code>&gt;&gt;&gt;</code> operator</a>. For instance:</p>\n\n\n\n<pre><code>&gt; (-1).toString(16)\n"-1"\n\n&gt; ((-2)&gt;&gt;&gt;0).toString(16)\n"fffffffe"\n</code></pre>\n\n<p>There is however one limitation: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Summary" rel="noreferrer" title="Bitwise Operators [MDN]">JavaScript bitwise operators treat their operands as a sequence of 32 bits</a>, that is, you get the 32-bits two\'s complement.</p>\n'}, {'answer_id': 20483568, 'author': 'realkstrawn93', 'author_id': 1118706, 'author_profile': 'https://Stackoverflow.com/users/1118706', 'pm_score': 2, 'selected': False, 'text': '<p>To sum it all up;</p>\n\n<pre><code>function toHex(i, pad) {\n\n  if (typeof(pad) === \'undefined\' || pad === null) {\n    pad = 2;\n  } \n\n  var strToParse = i.toString(16);\n\n  while (strToParse.length &lt; pad) {\n    strToParse = "0" + strToParse;\n  }\n\n  var finalVal =  parseInt(strToParse, 16);\n\n  if ( finalVal &lt; 0 ) {\n    finalVal = 0xFFFFFFFF + finalVal + 1;\n  }\n\n  return finalVal;\n}\n</code></pre>\n\n<p>However, if you don\'t need to convert it back to an integer at the end (i.e. for colors), then just making sure the values aren\'t negative should suffice.</p>\n'}, {'answer_id': 26784300, 'author': 'Mark Manning', 'author_id': 928121, 'author_profile': 'https://Stackoverflow.com/users/928121', 'pm_score': 5, 'selected': False, 'text': '<p>The accepted answer did not take into account single digit returned hexadecimal codes. This is easily adjusted by:</p>\n\n<pre><code>function numHex(s)\n{\n    var a = s.toString(16);\n    if ((a.length % 2) &gt; 0) {\n        a = "0" + a;\n    }\n    return a;\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>function strHex(s)\n{\n    var a = "";\n    for (var i=0; i&lt;s.length; i++) {\n        a = a + numHex(s.charCodeAt(i));\n    }\n\n    return a;\n}\n</code></pre>\n\n<p>I believe the above answers have been posted numerous times by others in one form or another. I wrap these in a toHex() function like so:</p>\n\n<pre><code>function toHex(s)\n{\n    var re = new RegExp(/^\\s*(\\+|-)?((\\d+(\\.\\d+)?)|(\\.\\d+))\\s*$/);\n\n    if (re.test(s)) {\n        return \'#\' + strHex( s.toString());\n    }\n    else {\n        return \'A\' + strHex(s);\n    }\n}\n</code></pre>\n\n<p>Note that the numeric regular expression came from <a href="http://ntt.cc/2008/05/10/over-10-useful-javascript-regular-expression-functions-to-improve-your-web-applications-efficiency.html" rel="noreferrer">10+ Useful JavaScript Regular Expression Functions to improve your web applications efficiency</a>.</p>\n\n<p>Update: After testing this thing several times I found an error (double quotes in the RegExp), so I fixed that.  HOWEVER! After quite a bit of testing and having read the post by almaz - I realized I could not get negative numbers to work. </p>\n\n<p>Further - I did some reading up on this and since all JavaScript numbers are stored as 64 bit words no matter what - I tried modifying the numHex code to get the 64 bit word. But it turns out you can not do that. If you put "3.14159265" AS A NUMBER into a variable - all you will be able to get is the "3", because the fractional portion is only accessible by multiplying the number by ten(IE:10.0) repeatedly. Or to put that another way - the <em>hexadecimal</em> value of 0xF causes the <em>floating point</em> value to be translated into an <em>integer</em> before it is ANDed which removes everything behind the period.  Rather than taking the value as a whole (i.e.: 3.14159265) and ANDing the <em>floating point</em> value against the 0xF value.</p>\n\n<p>So the best thing to do, in this case, is to convert the 3.14159265 into a <em>string</em> and then just convert the string. Because of the above, it also makes it easy to convert negative numbers because the minus sign just becomes 0x26 on the front of the value.</p>\n\n<p>So what I did was on determining that the variable contains a number - just convert it to a string and convert the string. This means to everyone that on the server side you will need to unhex the incoming string and then to determine the incoming information is numeric. You can do that easily by just adding a "#" to the front of numbers and "A" to the front of a character string coming back. See the toHex() function.</p>\n\n<p>Have fun!</p>\n\n<p>After another year and a lot of thinking, I decided that the "toHex" function (and I also have a "fromHex" function) really needed to be revamped. The whole question was "How can I do this more efficiently?" I decided that a to/from hexadecimal function should not care if something is a fractional part but at the same time it should ensure that fractional parts are included in the string.</p>\n\n<p>So then the question became, "How do you know you are working with a hexadecimal string?". The answer is simple. Use the standard pre-string information that is already recognized around the world.</p>\n\n<p>In other words - use "0x". So now my toHex function looks to see if that is already there and if it is - it just returns the string that was sent to it. Otherwise, it converts the string, number, whatever. Here is the revised toHex function:</p>\n\n<pre><code>/////////////////////////////////////////////////////////////////////////////\n//  toHex().  Convert an ASCII string to hexadecimal.\n/////////////////////////////////////////////////////////////////////////////\ntoHex(s)\n{\n    if (s.substr(0,2).toLowerCase() == "0x") {\n        return s;\n    }\n\n    var l = "0123456789ABCDEF";\n    var o = "";\n\n    if (typeof s != "string") {\n        s = s.toString();\n    }\n    for (var i=0; i&lt;s.length; i++) {\n        var c = s.charCodeAt(i);\n\n        o = o + l.substr((c&gt;&gt;4),1) + l.substr((c &amp; 0x0f),1);\n    }\n\n    return "0x" + o;\n}\n</code></pre>\n\n<p>This is a very fast function that takes into account single digits, floating point numbers, and even checks to see if the person is sending a hex value over to be hexed again. It only uses four function calls and only two of those are in the loop. To un-hex the values you use:</p>\n\n<pre><code>/////////////////////////////////////////////////////////////////////////////\n//  fromHex().  Convert a hex string to ASCII text.\n/////////////////////////////////////////////////////////////////////////////\nfromHex(s)\n{\n    var start = 0;\n    var o = "";\n\n    if (s.substr(0,2).toLowerCase() == "0x") {\n        start = 2;\n    }\n\n    if (typeof s != "string") {\n        s = s.toString();\n    }\n    for (var i=start; i&lt;s.length; i+=2) {\n        var c = s.substr(i, 2);\n\n        o = o + String.fromCharCode(parseInt(c, 16));\n    }\n\n    return o;\n}\n</code></pre>\n\n<p>Like the toHex() function, the fromHex() function first looks for the "0x" and then it translates the incoming information into a string if it isn\'t already a string.  I don\'t know how it wouldn\'t be a string - but just in case - I check. The function then goes through, grabbing two characters and translating those in to ASCII characters. If you want it to translate Unicode, you will need to change the loop to going by four(4) characters at a time. But then you also need to ensure that the string is NOT divisible by four. If it is - then it is a standard hexadecimal string. (Remember the string has "0x" on the front of it.)</p>\n\n<p>A simple test script to show that -3.14159265, when converted to a string, is still -3.14159265.</p>\n\n<pre><code>&lt;?php\n\n    echo &lt;&lt;&lt;EOD\n&lt;html&gt;\n    &lt;head&gt;&lt;title&gt;Test&lt;/title&gt;\n        &lt;script&gt;\n            var a = -3.14159265;\n            alert( "A = " + a );\n            var b = a.toString();\n            alert( "B = " + b );\n        &lt;/script&gt;\n    &lt;/head&gt;\n    &lt;body&gt;\n    &lt;/body&gt;\n&lt;/html&gt;\nEOD;\n\n?&gt;\n</code></pre>\n\n<p>Because of how JavaScript works in respect to the toString() function, all of those problems can be eliminated which before were causing problems. Now all strings and numbers can be converted easily. Further, such things as objects will cause an error to be generated by JavaScript itself. I believe this is about as good as it gets. The only improvement left is for W3C to just include a toHex() and fromHex() function in JavaScript.</p>\n'}, {'answer_id': 33622834, 'author': 'Hat', 'author_id': 2203482, 'author_profile': 'https://Stackoverflow.com/users/2203482', 'pm_score': 4, 'selected': False, 'text': '<p>For anyone interested, <a href="http://jsfiddle.net/t3z4tqy5/" rel="noreferrer">here\'s a JSFiddle comparing most of the answers given to this question</a>.</p>\n\n<p>And here\'s the method I ended up going with:</p>\n\n<pre class="lang-js prettyprint-override"><code>function decToHex(dec) {\n  return (dec + Math.pow(16, 6)).toString(16).substr(-6)\n}\n</code></pre>\n\n<hr>\n\n<p>Also, bear in mind that if you\'re looking to convert from decimal to hex for use in CSS as a <a href="https://developer.mozilla.org/en/docs/Web/CSS/color_value" rel="noreferrer">color data type</a>, you might instead prefer to extract the RGB values from the decimal and use <a href="https://developer.mozilla.org/en/docs/Web/CSS/color_value#rgb()" rel="noreferrer">rgb()</a>.</p>\n\n<p>For example (<a href="http://jsfiddle.net/6wzckyn9/" rel="noreferrer">JSFiddle</a>):</p>\n\n<pre class="lang-js prettyprint-override"><code>let c = 4210330 // your color in decimal format\nlet rgb = [(c &amp; 0xff0000) &gt;&gt; 16,  (c &amp; 0x00ff00) &gt;&gt; 8,  (c &amp; 0x0000ff)]\n\n// Vanilla JS:\ndocument..getElementById(\'some-element\').style.color = \'rgb(\' + rgb + \')\'\n// jQuery:\n$(\'#some-element\').css(\'color\', \'rgb(\' + rgb + \')\')\n</code></pre>\n\n<p>This sets <code>#some-element</code>\'s CSS <code>color</code> property to <code>rgb(64, 62, 154)</code>.</p>\n'}, {'answer_id': 35251679, 'author': 'JonLikeSquirrel', 'author_id': 5763792, 'author_profile': 'https://Stackoverflow.com/users/5763792', 'pm_score': 2, 'selected': False, 'text': "<p><strong>How to convert decimal to hexadecimal in JavaScript</strong></p>\n\n<p>I wasn't able to find a brutally clean/simple decimal to hexadecimal conversion that didn't involve a mess of functions and arrays ... so I had to make this for myself.</p>\n\n<pre><code>function DecToHex(decimal) { // Data (decimal)\n\n    length = -1;    // Base string length\n    string = '';    // Source 'string'\n\n    characters = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' ]; // character array\n\n    do { // Grab each nibble in reverse order because JavaScript has no unsigned left shift\n\n        string += characters[decimal &amp; 0xF];   // Mask byte, get that character\n        ++length;                              // Increment to length of string\n\n    } while (decimal &gt;&gt;&gt;= 4); // For next character shift right 4 bits, or break on 0\n\n    decimal += 'x'; // Convert that 0 into a hex prefix string -&gt; '0x'\n\n    do\n        decimal += string[length];\n    while (length--); // Flip string forwards, with the prefixed '0x'\n\n    return (decimal); // return (hexadecimal);\n}\n\n/* Original: */\n\nD = 3678;    // Data (decimal)\nC = 0xF;    // Check\nA = D;        // Accumulate\nB = -1;        // Base string length\nS = '';        // Source 'string'\nH = '0x';    // Destination 'string'\n\ndo {\n    ++B;\n    A&amp; = C;\n\n    switch(A) {\n        case 0xA: A='A'\n        break;\n\n        case 0xB: A='B'\n        break;\n\n        case 0xC: A='C'\n        break;\n\n        case 0xD: A='D'\n        break;\n\n        case 0xE: A='E'\n        break;\n\n        case 0xF: A='F'\n        break;\n\n        A = (A);\n    }\n    S += A;\n\n    D &gt;&gt;&gt;= 0x04;\n    A = D;\n} while(D)\n\ndo\n    H += S[B];\nwhile (B--)\n\nS = B = A = C = D; // Zero out variables\nalert(H);    // H: holds hexadecimal equivalent\n</code></pre>\n"}, {'answer_id': 47125022, 'author': 'Francisco Manuel Garca Botella', 'author_id': 4285108, 'author_profile': 'https://Stackoverflow.com/users/4285108', 'pm_score': 2, 'selected': False, 'text': '<p>I haven\'t found a clear answer, without checks if it is negative or positive, that uses two\'s complement (negative numbers included). For that, I show my solution to one byte:</p>\n\n<pre><code>((0xFF + number +1) &amp; 0x0FF).toString(16);\n</code></pre>\n\n<p>You can use this instruction to any number bytes, only you add <code>FF</code> in respective places. For example, to two bytes:</p>\n\n<pre><code>((0xFFFF + number +1) &amp; 0x0FFFF).toString(16);\n</code></pre>\n\n<p>If you want cast an array integer to string hexadecimal:</p>\n\n<pre><code>s = "";\nfor(var i = 0; i &lt; arrayNumber.length; ++i) {\n    s += ((0xFF + arrayNumber[i] +1) &amp; 0x0FF).toString(16);\n}\n</code></pre>\n'}, {'answer_id': 49264490, 'author': 'dhc', 'author_id': 2868394, 'author_profile': 'https://Stackoverflow.com/users/2868394', 'pm_score': 2, 'selected': False, 'text': "<p>In case you're looking to convert to a 'full' JavaScript or CSS representation, you can use something like:</p>\n\n<pre><code>  numToHex = function(num) {\n    var r=((0xff0000&amp;num)&gt;&gt;16).toString(16),\n        g=((0x00ff00&amp;num)&gt;&gt;8).toString(16),\n        b=(0x0000ff&amp;num).toString(16);\n    if (r.length==1) { r = '0'+r; }\n    if (g.length==1) { g = '0'+g; }\n    if (b.length==1) { b = '0'+b; }\n    return '0x'+r+g+b;                 // ('#' instead of'0x' for CSS)\n  };\n\n  var dec = 5974678;\n  console.log( numToHex(dec) );        // 0x5b2a96\n</code></pre>\n"}, {'answer_id': 53389207, 'author': 'Hypersoft Systems', 'author_id': 3370790, 'author_profile': 'https://Stackoverflow.com/users/3370790', 'pm_score': -1, 'selected': False, 'text': '<p>Here\'s my solution:</p>\n\n<pre><code>hex = function(number) {\n  return \'0x\' + Math.abs(number).toString(16);\n}\n</code></pre>\n\n<p>The question says: <em>"How to convert decimal to hexadecimal in JavaScript"</em>. While, the question does not specify that the hexadecimal string should begin with a 0x prefix, anybody who writes code should know that 0x is added to hexadecimal codes to distinguish <em>hexadecimal codes</em> from <em>programmatic identifiers</em> and <em>other numbers</em> (1234 could be hexadecimal, decimal, or even octal).</p>\n\n<p>Therefore, to correctly answer this question, for the purpose of script-writing, you must add the 0x prefix.</p>\n\n<p>The Math.abs(N) function converts negatives to positives, and as a bonus, it doesn\'t look like somebody ran it through a wood-chipper.</p>\n\n<p>The answer I wanted, would have had a field-width specifier, so we could for example show 8/16/32/64-bit values the way you would see them listed in a hexadecimal editing application. That, is the actual, correct answer.</p>\n'}, {'answer_id': 54441205, 'author': 'Alireza', 'author_id': 5423108, 'author_profile': 'https://Stackoverflow.com/users/5423108', 'pm_score': 2, 'selected': False, 'text': '<p>You can do something like this in <a href="https://en.wikipedia.org/wiki/ECMAScript#6th_Edition_-_ECMAScript_2015" rel="nofollow noreferrer">ECMAScript&nbsp;6</a>:</p>\n\n<pre><code>const toHex = num =&gt; (num).toString(16).toUpperCase();\n</code></pre>\n'}, {'answer_id': 56180356, 'author': 'Abhilash Nayak', 'author_id': 5950470, 'author_profile': 'https://Stackoverflow.com/users/5950470', 'pm_score': 2, 'selected': False, 'text': '<p>If you are looking for converting Large integers i.e. Numbers greater than Number.MAX_SAFE_INTEGER -- 9007199254740991, then you can use the following code</p>\n\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>const hugeNumber = "9007199254740991873839" // Make sure its in String\r\nconst hexOfHugeNumber = BigInt(hugeNumber).toString(16);\r\nconsole.log(hexOfHugeNumber)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 57551796, 'author': 'Brian', 'author_id': 2850957, 'author_profile': 'https://Stackoverflow.com/users/2850957', 'pm_score': 2, 'selected': False, 'text': '<p>This is based on Prestaul and Tod\'s solutions. However, this is a generalisation that accounts for varying size of a variable (e.g. Parsing signed value from a microcontroller serial log). </p>\n\n<pre><code>function decimalToPaddedHexString(number, bitsize)\n{ \n  let byteCount = Math.ceil(bitsize/8);\n  let maxBinValue = Math.pow(2, bitsize)-1;\n\n  /* In node.js this function fails for bitsize above 32bits */\n  if (bitsize &gt; 32)\n    throw "number above maximum value";\n\n  /* Conversion to unsigned form based on  */\n  if (number &lt; 0)\n    number = maxBinValue + number + 1;\n\n  return "0x"+(number &gt;&gt;&gt; 0).toString(16).toUpperCase().padStart(byteCount*2, \'0\');\n}\n</code></pre>\n\n<p>Test script:</p>\n\n<pre><code>for (let n = 0 ; n &lt; 64 ; n++ ) { \n     let s=decimalToPaddedHexString(-1, n); \n     console.log(`decimalToPaddedHexString(-1,${(n+"").padStart(2)}) = ${s.padStart(10)} = ${("0b"+parseInt(s).toString(2)).padStart(34)}`);\n   }\n</code></pre>\n\n<p>Test results:</p>\n\n<pre><code>decimalToPaddedHexString(-1, 0) =        0x0 =                                0b0\ndecimalToPaddedHexString(-1, 1) =       0x01 =                                0b1\ndecimalToPaddedHexString(-1, 2) =       0x03 =                               0b11\ndecimalToPaddedHexString(-1, 3) =       0x07 =                              0b111\ndecimalToPaddedHexString(-1, 4) =       0x0F =                             0b1111\ndecimalToPaddedHexString(-1, 5) =       0x1F =                            0b11111\ndecimalToPaddedHexString(-1, 6) =       0x3F =                           0b111111\ndecimalToPaddedHexString(-1, 7) =       0x7F =                          0b1111111\ndecimalToPaddedHexString(-1, 8) =       0xFF =                         0b11111111\ndecimalToPaddedHexString(-1, 9) =     0x01FF =                        0b111111111\ndecimalToPaddedHexString(-1,10) =     0x03FF =                       0b1111111111\ndecimalToPaddedHexString(-1,11) =     0x07FF =                      0b11111111111\ndecimalToPaddedHexString(-1,12) =     0x0FFF =                     0b111111111111\ndecimalToPaddedHexString(-1,13) =     0x1FFF =                    0b1111111111111\ndecimalToPaddedHexString(-1,14) =     0x3FFF =                   0b11111111111111\ndecimalToPaddedHexString(-1,15) =     0x7FFF =                  0b111111111111111\ndecimalToPaddedHexString(-1,16) =     0xFFFF =                 0b1111111111111111\ndecimalToPaddedHexString(-1,17) =   0x01FFFF =                0b11111111111111111\ndecimalToPaddedHexString(-1,18) =   0x03FFFF =               0b111111111111111111\ndecimalToPaddedHexString(-1,19) =   0x07FFFF =              0b1111111111111111111\ndecimalToPaddedHexString(-1,20) =   0x0FFFFF =             0b11111111111111111111\ndecimalToPaddedHexString(-1,21) =   0x1FFFFF =            0b111111111111111111111\ndecimalToPaddedHexString(-1,22) =   0x3FFFFF =           0b1111111111111111111111\ndecimalToPaddedHexString(-1,23) =   0x7FFFFF =          0b11111111111111111111111\ndecimalToPaddedHexString(-1,24) =   0xFFFFFF =         0b111111111111111111111111\ndecimalToPaddedHexString(-1,25) = 0x01FFFFFF =        0b1111111111111111111111111\ndecimalToPaddedHexString(-1,26) = 0x03FFFFFF =       0b11111111111111111111111111\ndecimalToPaddedHexString(-1,27) = 0x07FFFFFF =      0b111111111111111111111111111\ndecimalToPaddedHexString(-1,28) = 0x0FFFFFFF =     0b1111111111111111111111111111\ndecimalToPaddedHexString(-1,29) = 0x1FFFFFFF =    0b11111111111111111111111111111\ndecimalToPaddedHexString(-1,30) = 0x3FFFFFFF =   0b111111111111111111111111111111\ndecimalToPaddedHexString(-1,31) = 0x7FFFFFFF =  0b1111111111111111111111111111111\ndecimalToPaddedHexString(-1,32) = 0xFFFFFFFF = 0b11111111111111111111111111111111\nThrown: \'number above maximum value\'\n</code></pre>\n\n<p>Note: Not too sure why it fails above 32 bitsize</p>\n'}, {'answer_id': 65859562, 'author': 'Bohdan Sych', 'author_id': 4768564, 'author_profile': 'https://Stackoverflow.com/users/4768564', 'pm_score': 2, 'selected': False, 'text': "<ul>\n<li><p>rgb(255, 255, 255) // returns FFFFFF</p>\n</li>\n<li><p>rgb(255, 255, 300) // returns FFFFFF</p>\n</li>\n<li><p>rgb(0,0,0)         // returns 000000</p>\n</li>\n<li><p>rgb(148, 0, 211)   // returns 9400D3</p>\n<pre><code> function rgb(...values){\n          return values.reduce((acc, cur) =&gt; {\n            let val = cur &gt;= 255 ? 'ff' : cur &lt;= 0 ? '00' : Number(cur).toString(16);\n            return acc + (val.length === 1 ? '0'+val : val);\n          }, '').toUpperCase();\n      }\n</code></pre>\n</li>\n</ul>\n"}, {'answer_id': 66126345, 'author': 'Kamil Kiełczewski', 'author_id': 860099, 'author_profile': 'https://Stackoverflow.com/users/860099', 'pm_score': 0, 'selected': False, 'text': '<h1>Arbitrary precision</h1>\n<p>This solution take on input decimal string, and return hex string. A decimal fractions are supported. Algorithm</p>\n<ul>\n<li>split number to sign (<code>s</code>), integer part (<code>i</code>) and fractional part (<code>f</code>) e.g for <code>-123.75</code> we have <code>s=true</code>, <code>i=123</code>, <code>f=75</code></li>\n<li>integer part to hex:\n<ul>\n<li>if <code>i=\'0\'</code> stop</li>\n<li>get modulo: <code>m=i%16</code> (in arbitrary precision)</li>\n<li>convert <code>m</code> to hex digit and put to result string</li>\n<li>for next step calc integer part <code>i=i/16</code> (in arbitrary precision)</li>\n</ul>\n</li>\n<li>fractional part\n<ul>\n<li>count fractional digits <code>n</code></li>\n<li>multiply <code>k=f*16</code> (in arbitrary precision)</li>\n<li>split <code>k</code> to right part with <code>n</code> digits and put them to <code>f</code>, and left part with rest of digits and put them to <code>d</code></li>\n<li>convert <code>d</code> to hex and add to result.</li>\n<li>finish when number of result fractional digits is enough</li>\n</ul>\n</li>\n</ul>\n<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">\r\n<div class="snippet-code snippet-currently-hidden">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>// @param decStr - string with non-negative integer\n// @param divisor - positive integer\nfunction dec2HexArbitrary(decStr, fracDigits=0) {   \n    // Helper: divide arbitrary precision number by js number\n    // @param decStr - string with non-negative integer\n    // @param divisor - positive integer\n    function arbDivision(decStr, divisor) \n    { \n        // algorithm https://www.geeksforgeeks.org/divide-large-number-represented-string/\n        let ans=\'\'; \n        let idx = 0; \n        let temp = +decStr[idx]; \n        while (temp &lt; divisor) temp = temp * 10 + +decStr[++idx]; \n\n        while (decStr.length &gt; idx) { \n            ans += (temp / divisor)|0 ; \n            temp = (temp % divisor) * 10 + +decStr[++idx]; \n        } \n\n        if (ans.length == 0) return "0"; \n\n        return ans; \n    } \n\n    // Helper: calc module of arbitrary precision number\n    // @param decStr - string with non-negative integer\n    // @param mod - positive integer\n    function arbMod(decStr, mod) { \n      // algorithm https://www.geeksforgeeks.org/how-to-compute-mod-of-a-big-number/\n      let res = 0; \n\n      for (let i = 0; i &lt; decStr.length; i++) \n        res = (res * 10 + +decStr[i]) % mod; \n\n      return res; \n    } \n\n    // Helper: multiply arbitrary precision integer by js number\n    // @param decStr - string with non-negative integer\n    // @param mult - positive integer\n    function arbMultiply(decStr, mult) {\n      let r=\'\';\n      let m=0;\n      for (let i = decStr.length-1; i &gt;=0 ; i--) {\n        let n = m+mult*(+decStr[i]);\n        r= (i ? n%10 : n) + r \n        m= n/10|0;\n      }\n      return r;\n    }\n    \n    \n    // dec2hex algorithm starts here\n    \n    let h= \'0123456789abcdef\';                                         // hex \'alphabet\'\n    let m= decStr.match(/-?(.*?)\\.(.*)?/) || decStr.match(/-?(.*)/);   // separate sign,integer,ractional\n    let i= m[1].replace(/^0+/,\'\').replace(/^$/,\'0\');                   // integer part (without sign and leading zeros)\n    let f= (m[2]||\'0\').replace(/0+$/,\'\').replace(/^$/,\'0\');            // fractional part (without last zeros)\n    let s= decStr[0]==\'-\';                                                                             // sign\n\n    let r=\'\';                                                                                                          // result\n    \n    if(i==\'0\') r=\'0\';\n        \n    while(i!=\'0\') {                                                    // integer part\n      r=h[arbMod(i,16)]+r; \n      i=arbDivision(i,16);\n    }\n            \n    if(fracDigits) r+=".";\n        \n    let n = f.length;\n    \n    for(let j=0; j&lt;fracDigits; j++) {                                  // frac part\n      let k= arbMultiply(f,16);\n      f = k.slice(-n);\n      let d= k.slice(0,k.length-n); \n      r+= d.length ? h[+d] : \'0\';\n    }\n            \n    return (s?\'-\':\'\')+r;\n}\n\n\n\n\n\n\n\n\n// -----------\n// TESTS\n// -----------\n\n\n\nlet tests = [\n  ["0",2],\n  ["000",2],  \n  ["123",0],\n  ["-123",0],  \n  ["00.000",2],\n  \n  ["255.75",5],\n  ["-255.75",5], \n  ["127.999",32], \n];\n\nconsole.log(\'Input      Standard          Abitrary\');\ntests.forEach(t=&gt; {\n  let nonArb = (+t[0]).toString(16).padEnd(17,\' \');\n  let arb = dec2HexArbitrary(t[0],t[1]);\n  console.log(t[0].padEnd(10,\' \'), nonArb, arb); \n});\n\n\n// Long Example (40 digits after dot)\nlet example = "123456789012345678901234567890.09876543210987654321"\nconsole.log(`\\nLong Example:`);\nconsole.log(\'dec:\',example);\nconsole.log(\'hex:     \',dec2HexArbitrary(example,40));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 71171818, 'author': 'Wilt', 'author_id': 1697459, 'author_profile': 'https://Stackoverflow.com/users/1697459', 'pm_score': 2, 'selected': False, 'text': '<h2>Converting hex color numbers to hex color strings:</h2>\n<p>A simple solution with <code>toString</code> and ES6 <code>padStart</code> for converting hex color numbers to hex color strings.</p>\n<pre><code>const string = `#${color.toString(16).padStart(6, \'0\')}`;\n</code></pre>\n<p>For example:</p>\n<p><code>0x000000</code> will become <code>#000000</code><br>\n<code>0xFFFFFF</code> will become <code>#FFFFFF</code></p>\n<p><a href="https://jsfiddle.net/wilt/zg1vcbu3/" rel="nofollow noreferrer">Check this example in a fiddle here</a></p>\n'}, {'answer_id': 71523192, 'author': 'aGuegu', 'author_id': 1764290, 'author_profile': 'https://Stackoverflow.com/users/1764290', 'pm_score': 0, 'selected': False, 'text': '<p>The problem basically how many padding zeros to expect.</p>\n<p>If you expect string <code>01</code> and <code>11</code> from Number 1 and 17. it\'s better to use <a href="https://nodejs.org/docs/latest-v16.x/api/buffer.html" rel="nofollow noreferrer">Buffer</a> as a bridge, with which number is turn into bytes, and then the hex is just an output format of it. And the bytes organization is well controlled by Buffer functions, like <a href="https://nodejs.org/docs/latest-v16.x/api/buffer.html#bufwriteuint32bevalue-offset" rel="nofollow noreferrer">writeUInt32BE</a>, <a href="https://nodejs.org/docs/latest-v16.x/api/buffer.html#bufwriteint16levalue-offset" rel="nofollow noreferrer">writeInt16LE</a>, etc.</p>\n<pre class="lang-js prettyprint-override"><code>import { Buffer } from \'buffer\';\n\nfunction toHex(n) { // 4byte\n  const buff = Buffer.alloc(4);\n  buff.writeInt32BE(n);\n  return buff.toString(\'hex\');\n}\n\n</code></pre>\n<pre class="lang-sh prettyprint-override"><code>&gt; toHex(1)\n\'00000001\'\n&gt; toHex(17)\n\'00000011\'\n&gt; toHex(-1)\n\'ffffffff\'\n&gt; toHex(-1212)\n\'fffffb44\'\n&gt; toHex(1212)\n\'000004bc\'\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/57803', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5556/']