How do you convert decimal values to their hex equivalent in JavaScript?
|
|
Convert a number to a hexadecimal string with:
and reverse the process with:
|
|||||||||||||||||||||
|
|
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.
|
|||||||||||||||||
|
|
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.
|
||||
|
|||||||||||||||||||||
|
|
With padding:
|
|||
|
|
|
For completion, if you want the two's-complement hexadecimal representation of a negative number, you can use the zero-fill-right shift
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. |
|||||
|
|
Without the loop :
Also isn't it better not to use loop tests that have to be evaluated eg instead of:
have
|
||||
|
|
|
Combining some of these good ideas for an rgb to hex function (add the # elsewhere for html/css):
|
|||||
|
The 16 is the radix and there are 16 values in a hexadecimal number :-) |
||||
|
|
|
|||||||||||||
|
|
AFAIK comment 57807 is wrong and should be something like: var hex = Number(d).toString(16); instead of var hex = parseInt(d, 16);
|
||||
|
|
|
The accepted answer did not take into account single digit returned hex codes. This is easily adjusted by:
and
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:
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:
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:
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.
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. |
||||
|
|
|
Constrained/Padded to a set number of characters:
|
|||||
|
|
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:
|
|||
|
|
|
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:
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):
This sets |
|||
|
|
|
And if the number is negative? Here is my version.
|
|||
|
|
|
You can check the following JsFiddle example or Stackoverflow JS example code as well.
|
|||
|
|
|
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
It performs faster than |
|||
|
|
|
As the accepted answer states, the easiest way to convert from dec to hex is
To reverse the process you may also use the solution below, as it is even shorter.
It seems to be slower in Google Chrome and Firefox, but is significantly faster in Opera. See http://jsperf.com/hex-to-dec. |
|||
|
|
|
To sum it all up;
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. |
|||
|
|
|
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
|
|||||||||||||||||
|
protected by NINCOMPOOP Jul 29 '13 at 11:38
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?