Вопрос: Как преобразовать десятичное значение в hex в JavaScript?

Как вы конвертируете десятичные значения в их шестнадцатеричный эквивалент в JavaScript?




Преобразуйте число в шестнадцатеричную строку с помощью:

hexString = yourNumber.toString(16);

и отмените процесс:

yourNumber = parseInt(hexString, 16);


Если вам нужно обрабатывать такие вещи, как битовые поля или 32-битные цвета, вам нужно иметь дело с подписанными номерами. Функция javascript toString (16) вернет отрицательное шестнадцатеричное число, которое обычно не то, что вы хотите. Эта функция делает некоторое сумасшедшее дополнение, чтобы сделать его положительным числом.

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

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


Приведенный ниже код преобразует десятичное значение d в шестнадцатеричное. Он также позволяет добавлять дополнение к шестнадцатеричному результату. поэтому 0 по умолчанию станет 00.

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;


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


С прокладкой:

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


Для завершения, если вы хотите, чтобы комплемента дополнительного код шестнадцатеричное представление отрицательного числа, вы можете использовать сдвиг нулевой заливки вправо >>>оператор , Например:

> (-1).toString(16)

> ((-2)>>>0).toString(16)

Однако существует одно ограничение: Поразрядные операторы javascript обрабатывают свои операнды как последовательность из 32 бит , т. е. вы получаете 32-битное дополнение к двум.


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


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


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);
        return Number(0x1000000 + r[0]*0x10000 + r[1]*0x100 + r[2]).toString(16).substring(1);


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;


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


    echo <<<EOD
    var a = -3.14159265;
    alert( "A = " + a );
    var b = a.toString();
    alert( "B = " + b );


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.