# How to convert decimal to hex in JavaScript?

Luke Smith Source

How do you convert decimal values to their hex equivalent in JavaScript?

javascripthextostringbasenumber-formatting

answered 10 years ago Prestaul #1

Convert a number to a hexadecimal string with:

``````hexString = yourNumber.toString(16);
``````

and reverse the process with:

``````yourNumber = parseInt(hexString, 16);
``````

answered 10 years ago Luke Smith #2

The code below will convert the decimal value d to hex. It also allows you to add padding to the hex result. so 0 will become 00 by default.

``````function decimalToHex(d, padding) {
var hex = Number(d).toString(16);

hex = "0" + hex;
}

return hex;
}
``````

answered 10 years ago Danny Wilson #3

``````var number = 3200;
var hexString = number.toString(16);
``````

The 16 is the radix and there are 16 values in a hexadecimal number :-)

answered 9 years ago Tod #4

If you need to handle things like bit fields or 32-bit colors, then you need to deal with signed numbers. The javascript function `toString(16)` will return a negative hex number which is usually not what you want. This function does some crazy addition to make it a positive number.

``````function decimalToHexString(number)
{
if (number < 0)
{
number = 0xFFFFFFFF + number + 1;
}

return number.toString(16).toUpperCase();
}

console.log(decimalToHexString(27));
console.log(decimalToHexString(48.6));``````

answered 9 years ago Fred #5

``````function dec2hex(i)
{
var result = "0000";
if      (i >= 0    && i <= 15)    { result = "000" + i.toString(16); }
else if (i >= 16   && i <= 255)   { result = "00"  + i.toString(16); }
else if (i >= 256  && i <= 4095)  { result = "0"   + i.toString(16); }
else if (i >= 4096 && i <= 65535) { result =         i.toString(16); }
return result
}
``````

AFAIK comment 57807 is wrong and should be something like: var hex = Number(d).toString(16); instead of var hex = parseInt(d, 16);

``````function decimalToHex(d, padding) {
var hex = Number(d).toString(16);

hex = "0" + hex;
}

return hex;
}
``````

answered 8 years ago mystifeid #7

Without the loop :

``````function decimalToHex(d) {
var hex = Number(d).toString(16);
hex = "000000".substr(0, 6 - hex.length) + hex;
return hex;
}

//or "#000000".substr(0, 7 - hex.length) + hex;
//or whatever
//*Thanks to MSDN
``````

Also isn't it better not to use loop tests that have to be evaluated eg instead of:

``````for (var i = 0; i < hex.length; i++){}
``````

have

``````for (var i = 0, var j = hex.length; i < j; i++){}
``````

answered 7 years ago Fabio Ferrari #8

``````function dec2hex(i) {
return (i+0x10000).toString(16).substr(-4).toUpperCase();
}
``````

Constrained/Padded to a set number of characters:

``````function decimalToHex(decimal, chars) {
return (decimal + Math.pow(16, chars)).toString(16).slice(-chars).toUpperCase();
}
``````

answered 6 years ago korona #10

If you want to convert a number to a hex representation of an RGBA color value, I've found this to be the most useful combination of several tips from here:

``````        function toHexString(n) {
if(n < 0) {
n = 0xFFFFFFFF + n + 1;
}

return "0x" + ("00000000" + n.toString(16).toUpperCase()).substr(-8);
}
``````

answered 6 years ago Eliarh #11

And if the number is negative?

Here is my version.

``````function hexdec (hex_string) {
hex_string=((hex_string.charAt(1)!='X' && hex_string.charAt(1)!='x')?hex_string='0X'+hex_string : hex_string);
hex_string=(hex_string.charAt(2)<8 ? hex_string =hex_string-0x00000000 : hex_string=hex_string-0xFFFFFFFF-1);
return parseInt(hex_string, 10);
}
``````

answered 6 years ago Baznr #12

``````function toHex(d) {
return  ("0"+(Number(d).toString(16))).slice(-2).toUpperCase()
}
``````

answered 6 years ago Keith Mashinter #13

Combining some of these good ideas for an rgb to hex function (add the # elsewhere for html/css):

``````function rgb2hex(r,g,b) {
if (g !== undefined)
return Number(0x1000000 + r*0x10000 + g*0x100 + b).toString(16).substring(1);
else
return Number(0x1000000 + r[0]*0x10000 + r[1]*0x100 + r[2]).toString(16).substring(1);
}
``````

answered 6 years ago almaz #14

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

Simple `.toString(16)` 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 `symbols` defines the number of output symbols you want to get, that is for 4-byte integer it should be equal to 8):

``````var hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
function getHexRepresentation(num, symbols) {
var result = '';
while (symbols--) {
result = hex[num & 0xF] + result;
num >>= 4;
}
return result;
}
``````

It performs faster than `.toString(16)` on 1-2 byte numbers and slower on larger numbers (when `symbols` >= 6), but still should outperform methods that encode negative values properly.

answered 5 years ago R D #15

As the accepted answer states, the easiest way to convert from dec to hex is `var hex = dec.toString(16)`. However, you may prefer to add a string conversion, as it ensures that string representations like `"12".toString(16)` work correctly.

``````// avoids a hard to track down bug by returning `c` instead of `12`
(+"12").toString(16);
``````

To reverse the process you may also use the solution below, as it is even shorter.

``````var dec = +("0x" + hex);
``````

It seems to be slower in Google Chrome and Firefox, but is significantly faster in Opera. See http://jsperf.com/hex-to-dec.

answered 5 years ago Alberto #16

For completion, if you want the two's-complement hexadecimal representation of a negative number, you can use the zero-fill-right shift `>>>` operator. For instance:

``````> (-1).toString(16)
"-1"

> ((-2)>>>0).toString(16)
"fffffffe"
``````

There is however one limitation: javascript bitwise operators treat their operands as a sequence of 32 bits, that is, you get the 32-bits two's-complement.

answered 5 years ago strawn_04 #17

To sum it all up;

``````function toHex(i, pad) {

}

var strToParse = i.toString(16);

strToParse = "0" + strToParse;
}

var finalVal =  parseInt(strToParse, 16);

if ( finalVal < 0 ) {
finalVal = 0xFFFFFFFF + finalVal + 1;
}

return finalVal;
}
``````

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.

answered 4 years ago Mark Manning #18

The accepted answer did not take into account single digit returned hex codes. This is easily adjusted by:

``````   function numHex(s)
{
var a = s.toString(16);
if( (a.length % 2) > 0 ){ a = "0" + a; }
return a;
}
``````

and

``````   function strHex(s)
{
var a = "";
for( var i=0; i<s.length; i++ ){
a = a + numHex( s.charCodeAt(i) );
}

return a;
}
``````

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:

``````   function toHex(s)
{
var re = new RegExp( /^\s*(\+|-)?((\d+(\.\d+)?)|(\.\d+))\s*\$/ );

if( re.test(s) ){ return '#' + strHex( s.toString() ); }
else { return 'A' + strHex( s ); }
}
``````

Note that the numeric regular expression came from 10+ Useful JavaScript Regular Expression Functions to improve your web applications efficiency.

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. 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 HEX value of 0xf causes the FLOATING POINT value to be translated into an INTEGER before it is ANDed which removes everything behind the period. Rather than taking the value as a whole (ie: 3.14159265) and ANDing the FLOATING POINT value against the 0xf value. So the best thing to do, in this case, is to convert the 3.14159265 into a STRING 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. So what I did was on determining that the variable contains a number - just convert it to a string and convert the string. What this means to everyone is 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.

Have fun!

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 hex 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. 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. 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:

``````/////////////////////////////////////////////////////////////////////////////
//  toHex().  Convert an ASCII string to hexadecimal.
/////////////////////////////////////////////////////////////////////////////
toHex(s)
{
if( s.substr(0,2).toLowerCase() == "0x" ){ return s; }

var l = "0123456789ABCDEF";
var o = "";

if( typeof s != "string" ){ s = s.toString(); }
for( var i=0; i<s.length; i++ ){
var c = s.charCodeAt(i);

o = o + l.substr((c>>4),1) + l.substr((c & 0x0f),1);
}

return "0x" + o;
}
``````

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:

``````/////////////////////////////////////////////////////////////////////////////
//  fromHex().  Convert a hex string to ascii text.
/////////////////////////////////////////////////////////////////////////////
fromHex(s)
{
var start = 0;
var o = "";

if( s.substr(0,2) == "0x" ){ start = 2; }

if( typeof s != "string" ){ s = s.toString(); }
for( var i=start; i<s.length; i+=2 ){
var c = s.substr( i, 2 );

o = o + String.fromCharCode( parseInt(c, 16) );
}

return o;
}
``````

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 divisable by four. If it is - then it is a standard hex string. (Remember the string has "0x" on the front of it.)

A simple test script to show that -3.14159265, when converted to a string, is still -3.14159265.

``````<?php

echo <<<EOD
<html>
<script>
var a = -3.14159265;
alert( "A = " + a );
var b = a.toString();
alert( "B = " + b );
</script>
<body>
</body>
</html>
EOD;

?>
``````

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

answered 3 years ago Hat #19

For anyone interested, here's a JSFiddle comparing most of the answers given to this question.

And here's the method I ended up going with:

``````function decToHex(dec) {
return (dec + Math.pow(16, 6)).toString(16).substr(-6);
}
``````

Also, bear in mind that if you're looking to convert from decimal to hex for use in CSS as a color data type, you might instead prefer to extract the RGB values from the decimal and use rgb().

For example (JSFiddle):

``````var c = 4210330; // your color in decimal format
var rgb = [(c & 0xff0000) >> 16,  (c & 0x00ff00) >> 8,  (c & 0x0000ff)];

// assuming you're using jQuery...
\$("#some-element").css("color", "rgb(" + rgb + ")");
``````

This sets `#some-element`'s CSS `color` property to `rgb(64, 62, 154)`.

answered 3 years ago JonLikeSquirrel #20

How to convert decimal to hex in JavaScript?

I know this question is old, wasn't able to find a brutally clean/simple Dec to Hex conversion that didn't involve a mess of functions and arrays ... so I had to make this for myself. Posting this to help anyone looking for this, know it would have saved me some time. lol

``````/* Revision: modified coding style, with array instead of a switch. */

function DecToHex( decimal ){ // Data (decimal)

length = -1;    // Base string length
string = '';    // Source 'string'

charactor = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' ]; // charactor array

do { // grab each nibble in reverse order because javscript has no unsigned left shift

string += charactor[ decimal & 0xF ];   // mask byte, get that charactor
++length;                               // incriment to length of string

} while( decimal >>>= 4 ); // for next char shift right 4 bits, or break on 0

decimal += 'x'; // convert that 0 into a hex prefix string -> '0x'

do decimal += string[ length ]; while( length-- ); // flip string forwards, with the prefixed '0x'

return ( decimal ); // return( hexadecial );

}

/* Original: */

D = 3678;   // Data (decimal)
C = 0xF;    // Check
A = D;      // Accumulate
B = -1;     // Base string length
S = '';     // Source 'string'
H = '0x';   // Destination 'string'

do{
++B;
A&=C;

switch(A){
case 0xA:A='A'
break;
case 0xB:A='B'
break;
case 0xC:A='C'
break;
case 0xD:A='D'
break;
case 0xE:A='E'
break;
case 0xF:A='F'
break;
A=(A);
}S+=A;

D>>>=0x04;
A=D;
}while(D) do H+=S[B];while(B--)

S = B = A = C = D; // Zero out variables
alert( H ); // H: holds hex equivalent
``````

answered 2 years ago Umar Abbas #21

You can check the following JsFiddle example or Stackoverflow JS example code as well.

``````'use strict';

var convertBase = function () {

function convertBase(baseFrom, baseTo) {
return function (num) {
return parseInt(num, baseFrom).toString(baseTo);

};
}

convertBase.dec2hex = convertBase(10, 16);
return convertBase;
}();

answered 11 months ago Francisco Manuel Garca Botella #22

I know this question is old, but I haven't found an clear answer, without checks if is negative or positive, that uses Two's complement (negative numbers included). For that, I show my solution to one byte:

``````((0xFF + number +1) & 0x0FF).toString(16);
``````

You can use this instruction to any number bytes, only you add FF in respective places. For example, to 2 bytes:

``````((0xFFFF + number +1) & 0x0FFFF).toString(16);
``````

If you want cast array integer to string hex:

``````s = "";
for(var i = 0; i < arrayNumber.length; ++i) {
s += ((0xFF + arrayNumber[i] +1) & 0x0FF).toString(16);
}
``````

Sorry for reactive an old thread.

answered 9 months ago Humoyun #23

Ok, the answer has already been given, this is complimentary. Here's a trimmed down ES6 version:

``````const convert = {
bin2dec : s => parseInt(s, 2).toString(10),
bin2hex : s => parseInt(s, 2).toString(16),
dec2bin : s => parseInt(s, 10).toString(2),
dec2hex : s => parseInt(s, 10).toString(16),
hex2bin : s => parseInt(s, 16).toString(2),
hex2dec : s => parseInt(s, 16).toString(10)
};

convert.bin2dec('111'); // '7'
convert.dec2hex('42');  // '2a'
convert.hex2bin('f8');  // '11111000'
convert.dec2bin('22');  // '10110'
``````

answered 6 months ago dhc #24

In case you're looking to convert to a 'full' JS or CSS representation, you can use something like:

``````  numToHex = function(num) {
var r=((0xff0000&num)>>16).toString(16),
g=((0x00ff00&num)>>8).toString(16),
b=(0x0000ff&num).toString(16);
if (r.length==1) { r = '0'+r; }
if (g.length==1) { g = '0'+g; }
if (b.length==1) { b = '0'+b; }
return '0x'+r+g+b;                 // ('#' instead of'0x' for CSS)
};

var dec = 5974678;
console.log( numToHex(dec) );        // 0x5b2a96
``````