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

Convert a number to a hexadecimal string with:

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

and reverse the process with:

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

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);
padding = typeof (padding) === "undefined" || padding === null ? padding = 2 : padding;
while (hex.length < padding) {
hex = "0" + hex;
}
return hex;
}
```

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

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

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

```
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);
padding = typeof (padding) === "undefined" || padding === null ? padding = 2 : padding;
while (hex.length < padding) {
hex = "0" + hex;
}
return hex;
}
```

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++){}
```

With padding:

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

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

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

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

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

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.

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.

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.

To sum it all up;

```
function toHex(i, pad) {
if (typeof(pad) === 'undefined' || pad === null) {
pad = 2;
}
var strToParse = i.toString(16);
while (strToParse.length < pad) {
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.

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!

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

.

**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

```
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
```

P.S. Wrap it in a function if needed, put the decimal number to be converted in "D" and the hexadecimal equivalent will come out at var "H". It should be self explanatory ... would assume runs very fast, you can also add padding if needed it will automatically adjust to the size of the decimal number you input. basic 32bit int being the max *No extra padding*

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);
};
}
// decimal to hexadecimal
convertBase.dec2hex = convertBase(10, 16);
return convertBase;
}();
alert(convertBase.dec2hex('42')); // '2a'
```

Similar Questions

I have integer number in ex. 16 and i am trying to convert this number to a hex number. I tried to achieve this by using hex function but whenever you provide a integer number to the hex function it r

I have some hex data: 48|65|6c|6c|6f|20|53|68|61|72|6f|6b|2e| 20|3d|43|46|3d|46|30|3d|45|38|3d|45|32|3d|45|35|3d|46|32|0d|0a|0d|0a|2e|0d|0a| The first text string is Hello Sharok (without quotes).

The number is bigger than int & long but can be accomodated in Decimal. But the normal ToString or Convert methods don't work on Decimal.

I need to communicate between Javascript and PHP (I use jquery for ajax) but the output of PHP script may contain binary data. That's why I use function bin2hex in PHP. Then json_encode is applied on

I have the following: int num=500; char text[8]; how do I make it so that text ends up being the hex 0x500, or 1280? edit: i see that its pretty simple to make it text, like in some of the answers. B

I have some perl code where hex() function converts hex data to decimal. How can i do it on python?

Possible Duplicate: How to convert a color integer to a hex String in Android? int c = bitmap.getPixel(x, y); returns a 7 or 8 digit number like -14438067 for green for example. How do I convert it

Im building a server in python, i need to convert a decimal value to hex like this : let's say the packet start by 4 bytes which define the packet lenght : 00 00 00 00 if the len(packet) = 255 we woul

I have a requirement of having a string which has a decimal value. For e.g., '0 2930 0'. Now , when i convert it to hex, it should say '0000 0B72 0000'. i'm able to convert the values to hex using spl

I was wondering how to convert a decimal into a fraction in its lowest form in Python. For example: 0.25 -> 1/4 0.5 -> 1/2 1.25 -> 5/4 3 -> 3/1

I am using Perl I got a string agn\u00e8s b How can I convert it to agnès b I have tried to use below code my $hex = agn\u00e8s b; $hex =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack(C,hex($1))/eg; pri

is there an easy way to convert an ASCII std::string to HEX? I don't want to convert it to a number, I only want to convert each ASCII character to it's HEX value. The output format should also be a s

I'm given a string hex_txt containing a 4 digit hex number in the way outlined in the code, split up in two array entries. I need to convert it to decimal. The following is the way I'm doing it. unsig

I have tried to Google quite a while now for an answer why HTML entities can be compiled either in HTML decimal or HTML hex. So my questions are: What is the difference between HTML decimal and HTML

I want to convert double precision numbers to decimal . for example I have 23.43, the double value would be (using matlab) : 174 71 255 122 20 110 55 64 now having this how can I write a java program

i am trying to understand how to convert/decode a Hex Value in the MS-DOS: 32 bit format into human readable Date & Time. i have found a way to do this with Unix Hex timestamp/epoch to a normal da

I suspect this might be a duplicate but lord if I can find it. I need to convert a 'mostly' hex value passed in the _GET[] array from string to an actual hex integer. I say 'mostly' because the hex nu

may be it is a simple question but I'm try all of conversion method! and it still has error! would you help me? decimal? (nullable decimal) to decimal

How to do decimal validation using javascript? there is a text box which should accept only 24.00 or 24 or any value less than 24.00 the text also must allow if 23.99 is entered. could some one help m

This seems to be an easy problem but i can't figure out. I need to convert this character < in byte(hex representation), but if i use byte b = Convert.ToByte('<'); i get 60 (decimal representat

How can i write in registry DWORD hexadecimal value ? Instead of decimal value, like in this code example ? RegistryKey key = Registry.LocalMachine; key = klase.CreateSubKey(@SYSTEM\CurrentControlSet

How do I convert a hex string to an int in Python? I may have it as 0xffff or just ffff.

So i want to be able to convert any decimal number into fraction. In both forms such as one without remainder like this: 3/5 or with remainder: 3 1/4. what i was doing is this.. lets say i have number

Possible Duplicate: How do you convert Byte Array to Hexadecimal String, and vice versa, in C#? Can we convert a hex string to a byte array using a built-in function in C# or do I have to make a cus

I have the following code in Java: int hex = 0x63; The decimal value of 6316 is equal to 9910. I would like to convert this hex value to a decimal that is equal to 6310.

I must admit I don't remember much about HEX and so on from school (25 years ago). In any case, I have some values in decimal format which I need to convert into HEX. I am using Excel but I could writ

I have a hexadecimal color value and I want to convert it to a UIColor. UIColor can take in a Hue/Saturation/Brightness (HSB) value or a Red/Blue/Green (RGB) value. How can I use the hex value to crea

Im very new html, javascript, and css so please forgive if my question sounds idiotic to you. My question is how can I prevent the function toFixed() from rounding of the decimal number. Here's my lin

How to convert GPS degrees, minutes, seconds to degrees with ONLY the minutes and seconds converted to decimal??

I already know how to convert hex to decimal, but I can't figure out the opposite. I need a function to convert a decimal value to hex then write it into the registry with RegWriteBinaryValue.

I need to convert hex->dec using groovy, i have def hex = 0x15B546EF13361F7B530C59332C60C2CE int i= Integer.parseInt(hex,16); When i run this, the error is actually showing me the value i need, b

In javaScript (within Photoshop) when giving a hex colour a value it's in quotes eg FCAA00 var hexCol = FCAA00; var fgColor = new SolidColor; fgColor.rgb.hexValue = hexCol but when passing a var

Anyone know of a good snippet of JavaScript code to convert HEX encoded strings to base64 encoded strings?

I have the binary number 1010 1011. I know that this is AB in hex and I know that A = 10 and B = 11 in decimal. But how do I get from 10 and 11 in decimal to the final number of 171? With hex I would

How to convert a big Hex number (in string format): EC851A69B8ACD843164E10CFF70CF9E86DC2FEE3CF6F374B43C854E3342A2F1AC3E30C741CC41E679DF6D07CE6FA3A66083EC9B8C8BF3AF05D8BDBB0AA6CB3EF8C5BAA2A5E531BA9E

All I really know is PHP and I used the decbin function etc, It was fairly easy to do. In this C++ program I want to do the same thing, just a simple number or string how would I do this?

How to convert the decimal 37 to the hex Value 25 in Erlang? Is there a simple way?

How would I convert a string that represents an integer like 4322566 to a hex string?

I have a decimal value of a utf-32 character: $a=21644; How can I convert this using php to a string of the hex? '548c' Here is the page for the codes I am using: http://www.fileformat.info/info/unic

How to convert X.509 certificate from a hex-dump form to .CER format? Additionally, should be blank space separators removed from hex dump first? Thanks.

I have a value stored in a short int that only makes sense when represented as hexadecimal digits with a decimal point. To exemplify: if the short int contains 1132 decimal (534h), then I need to outp

I need to convert code hex such as ” to its associated character, which is ” using php. Thanks in advance.

My fiddle - http://jsbin.com/pitu/1/edit I wanted to try an easy hex to rgba conversion. Ever browser I've used renders colors using rgb as default so when using the farbtastic color picker I'm conver

I have a hex string and i want to convert it utf8 to insert mysql. (my database is utf8) hex_string = 'kitap ara\xfet\xfdrmas\xfd' .. .. .. result='kitap araştırması' How can i do that? Best regards.

How do I convert a 10 digit number to a hex string in c#? Note: if the number is less than 10 digits, I want to add padding? example the number is 1, I want my string to be 0000000001.

input element contains numbers where comma or dot is used as decimal separator and space may me used to group thousands like '1,2' '110 000,23' '100 1.23' how to convert them to number in browser in j

Is there an algorithm (I've searched and haven't come up with much) that, given a hex value, is capable of returning the color name? It doesn't have to be anything too specific, any shade of blue comi

How can you convert a string value to decimal code point in xCode? What type of encoding can I use to convert these to the correct representation? Examples: string: 9 in decimal code point encoding is

I have a string 0.30405 and I need to convert it to a decimal. However it's throwing an error. What is the solution for this without blowing my head off Convert.ToDecimal(0.25500000) //throws exce

I have a decimal value say 123.77 Now i want to convert it into corresponding degree, minute, second value using MySQL. I tried several ways but can't get the right answer. please help.