如何在JavaScript中将十进制转换为十六进制?

时间:2022-10-30 14:58:49

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

如何将十进制值转换为JavaScript中的十六进制等效值?

24 个解决方案

#1


1895  

Convert a number to a hexadecimal string with:

将数字转换为十六进制字符串:

hexString = yourNumber.toString(16);

and reverse the process with:

并将流程反向:

yourNumber = parseInt(hexString, 16);

#2


114  

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.

如果您需要处理像位域或32位颜色这样的东西,那么您需要处理有符号的数字。javascript函数toString(16)将返回一个负十六进制数,这通常不是您想要的。这个函数做了一些疯狂的加法,使它成为正数。

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

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

#3


66  

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.

下面的代码将把十进制值转换为十六进制。它还允许您为十六进制结果添加填充。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;
}

#4


43  

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

#5


30  

With padding:

填充:

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

#6


25  

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.

但是有一个限制:javascript位操作符将其操作数作为32位的序列处理,也就是说,您得到32位的两个补码。

#7


16  

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

#8


13  

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

将这些好的想法结合到一个rgb到十六进制函数(在其他地方为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);
}

#9


10  

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

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

16是基数,十六进制数有16个值:-)

#10


10  

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:

我相信以上的答案已经被他人以不同的形式发布过无数次了。我用toHex()函数把它们包装起来:

   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.

注意,数值正则表达式来自10+有用的JavaScript正则表达式函数,以提高web应用程序的效率。

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.

更新:经过多次测试之后,我发现了一个错误(RegExp中的双引号),所以我修正了这个错误。然而!经过了相当多的测试,并阅读了almaz的帖子,我意识到我不能让负数工作。此外,我在这方面做了一些阅读,因为无论如何,所有的Javascript数字都被存储为64位字——我尝试修改numHex代码以得到64位的单词。但事实证明你不能这么做。如果你把“3.14159265”作为一个数字放入一个变量中,你可以得到的是“3”,因为分数部分只能通过将数字乘以10(即10.0)来得到。或者换一种说法——0xf的十六进制值使浮点值被转换成整数,然后再将所有的东西都删除。而不是将值作为一个整体(例如:3.14159265),并将浮点值与0xf值相结合。所以最好的方法是,把3。14159265转换成一个字符串然后转换字符串。由于上面的原因,它也使得转换负数变得容易,因为在值的前面,负号就变成了0x26。所以我所做的是确定变量包含一个数字——只是把它转换成一个字符串并转换字符串。这对每个人来说意味着,在服务器端,您需要将传入的字符串分解,然后确定传入的信息是数字的。只要在数字前面加上一个“#”,然后在返回的字符串前面加上“a”,就可以轻松做到这一点。看到toHex()函数。

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”功能(我还有一个“fromHex”功能)真的需要修改。整个问题是“我怎样才能更有效地做到这一点?”我认为,a /from hex函数不应该关心某个东西是否是小数部分,但同时它应该确保在字符串中包含小数部分。于是,问题变成了:“你怎么知道你在处理十六进制字符串?”答案很简单。使用已经在世界范围内已经确认的标准的预字符串信息。换句话说——使用“0x”。现在我的toHex函数看看它是否已经在那里了如果它是-它只返回发送给它的字符串。否则,它会转换字符串,数字,等等。这是修改后的toHex函数:

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

与toHex()函数一样,fromHex()函数首先查找“0x”,然后它将传入的信息转换为字符串,如果它不是字符串的话。我不知道它怎么会不是一个字符串,但以防万一——我检查一下。然后,这个函数会经过,抓住两个字符并将它们转换成ascii字符。如果您希望它转换unicode,那么您将需要一次修改循环一次4个字符。但是你还需要确保字符串不能被4分割。如果是-那么它就是一个标准的十六进制字符串。(记住,字符串前面有“0x”。)

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

一个简单的测试脚本显示-3.14159265,当转换为字符串时,仍然是-3.14159265。

<?php

    echo <<<EOD
<html>
<head><title>Test</title>
<script>
    var a = -3.14159265;
    alert( "A = " + a );
    var b = a.toString();
    alert( "B = " + b );
</script>
</head>
<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.

由于Javascript在toString()函数方面的工作方式,所有这些问题都可以在产生问题之前消除。现在所有的字符串和数字都可以轻松转换。此外,诸如对象之类的东西会导致由Javascript本身生成的错误。我相信这是最好的。惟一的改进是,W3C只需要在Javascript中包含toHex()和fromHex()函数。

#11


8  

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
}

#12


7  

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

AFAIK注释57807是错误的,应该是:var hex = Number(d).toString(16);而不是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;
}

#13


7  

Constrained/Padded to a set number of characters:

约束/填充到一个集合的字符数:

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

#14


6  

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:

如果您想要将一个数字转换为一个RGBA颜色值的十六进制表示,我发现这是以下几个技巧中最有用的组合:

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

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

#15


6  

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

对于任何感兴趣的人来说,这里是一个JSFiddle,比较了这个问题的大部分答案。

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

另外,请记住,如果您希望将CSS转换为十六进制,以便将其用作颜色数据类型,那么您可能更倾向于从decimal中提取RGB值,并使用RGB()。

For example (JSFiddle):

例如(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).

这将# someelement的CSS颜色属性设置为rgb(64, 62, 154)。

#16


5  

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

#17


5  

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

您可以查看以下JsFiddle示例或* JS示例代码。

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

#18


3  

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

我在一个相当大的循环中转换到十六进制字符串,所以我尝试了几种技术以找到最快的。我的要求是得到一个固定长度的字符串作为结果,并正确地编码负值(-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):

简单。tostring(16)对我不起作用,因为我需要正确编码的负值。下面的代码是我迄今为止在1-2字节值上测试过的最快的代码(请注意,符号定义了您想要得到的输出符号的数量,这是4字节整数,它应该等于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.

它比. tostring(16)在1-2字节的数字上执行得更快,在更大的数字上(当符号>= 6时)更慢,但是仍然要优于正确编码负值的方法。

#19


3  

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.

作为被接受的答案状态,从dec到hex的最简单的转换方法是var hex = dec.toString(16)。但是,您可能更喜欢添加一个字符串转换,因为它确保字符串表示方式如“12”. tostring(16)正确工作。

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

在谷歌Chrome和Firefox中,它的速度似乎要慢一些,但在Opera中却要快得多。见http://jsperf.com/hex-to-dec。

#20


3  

How to convert decimal to hex in JavaScript?

如何在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

我知道这个问题已经过时了,无法找到一个非常干净/简单的Dec到十六进制转换,它不涉及功能和数组的混乱……所以我必须自己做这个。把这篇文章贴上去帮助别人,知道这将会节省我一段时间。哈哈

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

#21


2  

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.

但是,如果您不需要将其转换为最终的整数(即颜色),那么只需确保这些值不是负数就足够了。

#22


2  

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

好的,答案已经给出了,这是免费的。这是一个精简的ES6版本:

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' 

#23


1  

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:

您可以将此指令用于任何数字字节,只在各自的位置添加FF。例如,2字节:

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

If you want cast array integer to string hex:

如果您想要将数组整数转换为字符串hex:

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

Sorry for reactive an old thread.

不好意思,这是一个旧线程。

#24


0  

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

如果你想要转换成一个“完整”的JS或CSS表示,你可以使用如下的东西:

  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

#1


1895  

Convert a number to a hexadecimal string with:

将数字转换为十六进制字符串:

hexString = yourNumber.toString(16);

and reverse the process with:

并将流程反向:

yourNumber = parseInt(hexString, 16);

#2


114  

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.

如果您需要处理像位域或32位颜色这样的东西,那么您需要处理有符号的数字。javascript函数toString(16)将返回一个负十六进制数,这通常不是您想要的。这个函数做了一些疯狂的加法,使它成为正数。

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

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

#3


66  

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.

下面的代码将把十进制值转换为十六进制。它还允许您为十六进制结果添加填充。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;
}

#4


43  

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

#5


30  

With padding:

填充:

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

#6


25  

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.

但是有一个限制:javascript位操作符将其操作数作为32位的序列处理,也就是说,您得到32位的两个补码。

#7


16  

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

#8


13  

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

将这些好的想法结合到一个rgb到十六进制函数(在其他地方为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);
}

#9


10  

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

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

16是基数,十六进制数有16个值:-)

#10


10  

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:

我相信以上的答案已经被他人以不同的形式发布过无数次了。我用toHex()函数把它们包装起来:

   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.

注意,数值正则表达式来自10+有用的JavaScript正则表达式函数,以提高web应用程序的效率。

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.

更新:经过多次测试之后,我发现了一个错误(RegExp中的双引号),所以我修正了这个错误。然而!经过了相当多的测试,并阅读了almaz的帖子,我意识到我不能让负数工作。此外,我在这方面做了一些阅读,因为无论如何,所有的Javascript数字都被存储为64位字——我尝试修改numHex代码以得到64位的单词。但事实证明你不能这么做。如果你把“3.14159265”作为一个数字放入一个变量中,你可以得到的是“3”,因为分数部分只能通过将数字乘以10(即10.0)来得到。或者换一种说法——0xf的十六进制值使浮点值被转换成整数,然后再将所有的东西都删除。而不是将值作为一个整体(例如:3.14159265),并将浮点值与0xf值相结合。所以最好的方法是,把3。14159265转换成一个字符串然后转换字符串。由于上面的原因,它也使得转换负数变得容易,因为在值的前面,负号就变成了0x26。所以我所做的是确定变量包含一个数字——只是把它转换成一个字符串并转换字符串。这对每个人来说意味着,在服务器端,您需要将传入的字符串分解,然后确定传入的信息是数字的。只要在数字前面加上一个“#”,然后在返回的字符串前面加上“a”,就可以轻松做到这一点。看到toHex()函数。

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”功能(我还有一个“fromHex”功能)真的需要修改。整个问题是“我怎样才能更有效地做到这一点?”我认为,a /from hex函数不应该关心某个东西是否是小数部分,但同时它应该确保在字符串中包含小数部分。于是,问题变成了:“你怎么知道你在处理十六进制字符串?”答案很简单。使用已经在世界范围内已经确认的标准的预字符串信息。换句话说——使用“0x”。现在我的toHex函数看看它是否已经在那里了如果它是-它只返回发送给它的字符串。否则,它会转换字符串,数字,等等。这是修改后的toHex函数:

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

与toHex()函数一样,fromHex()函数首先查找“0x”,然后它将传入的信息转换为字符串,如果它不是字符串的话。我不知道它怎么会不是一个字符串,但以防万一——我检查一下。然后,这个函数会经过,抓住两个字符并将它们转换成ascii字符。如果您希望它转换unicode,那么您将需要一次修改循环一次4个字符。但是你还需要确保字符串不能被4分割。如果是-那么它就是一个标准的十六进制字符串。(记住,字符串前面有“0x”。)

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

一个简单的测试脚本显示-3.14159265,当转换为字符串时,仍然是-3.14159265。

<?php

    echo <<<EOD
<html>
<head><title>Test</title>
<script>
    var a = -3.14159265;
    alert( "A = " + a );
    var b = a.toString();
    alert( "B = " + b );
</script>
</head>
<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.

由于Javascript在toString()函数方面的工作方式,所有这些问题都可以在产生问题之前消除。现在所有的字符串和数字都可以轻松转换。此外,诸如对象之类的东西会导致由Javascript本身生成的错误。我相信这是最好的。惟一的改进是,W3C只需要在Javascript中包含toHex()和fromHex()函数。

#11


8  

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
}

#12


7  

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

AFAIK注释57807是错误的,应该是:var hex = Number(d).toString(16);而不是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;
}

#13


7  

Constrained/Padded to a set number of characters:

约束/填充到一个集合的字符数:

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

#14


6  

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:

如果您想要将一个数字转换为一个RGBA颜色值的十六进制表示,我发现这是以下几个技巧中最有用的组合:

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

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

#15


6  

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

对于任何感兴趣的人来说,这里是一个JSFiddle,比较了这个问题的大部分答案。

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

另外,请记住,如果您希望将CSS转换为十六进制,以便将其用作颜色数据类型,那么您可能更倾向于从decimal中提取RGB值,并使用RGB()。

For example (JSFiddle):

例如(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).

这将# someelement的CSS颜色属性设置为rgb(64, 62, 154)。

#16


5  

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

#17


5  

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

您可以查看以下JsFiddle示例或* JS示例代码。

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

#18


3  

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

我在一个相当大的循环中转换到十六进制字符串,所以我尝试了几种技术以找到最快的。我的要求是得到一个固定长度的字符串作为结果,并正确地编码负值(-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):

简单。tostring(16)对我不起作用,因为我需要正确编码的负值。下面的代码是我迄今为止在1-2字节值上测试过的最快的代码(请注意,符号定义了您想要得到的输出符号的数量,这是4字节整数,它应该等于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.

它比. tostring(16)在1-2字节的数字上执行得更快,在更大的数字上(当符号>= 6时)更慢,但是仍然要优于正确编码负值的方法。

#19


3  

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.

作为被接受的答案状态,从dec到hex的最简单的转换方法是var hex = dec.toString(16)。但是,您可能更喜欢添加一个字符串转换,因为它确保字符串表示方式如“12”. tostring(16)正确工作。

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

在谷歌Chrome和Firefox中,它的速度似乎要慢一些,但在Opera中却要快得多。见http://jsperf.com/hex-to-dec。

#20


3  

How to convert decimal to hex in JavaScript?

如何在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

我知道这个问题已经过时了,无法找到一个非常干净/简单的Dec到十六进制转换,它不涉及功能和数组的混乱……所以我必须自己做这个。把这篇文章贴上去帮助别人,知道这将会节省我一段时间。哈哈

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

#21


2  

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.

但是,如果您不需要将其转换为最终的整数(即颜色),那么只需确保这些值不是负数就足够了。

#22


2  

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

好的,答案已经给出了,这是免费的。这是一个精简的ES6版本:

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' 

#23


1  

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:

您可以将此指令用于任何数字字节,只在各自的位置添加FF。例如,2字节:

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

If you want cast array integer to string hex:

如果您想要将数组整数转换为字符串hex:

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

Sorry for reactive an old thread.

不好意思,这是一个旧线程。

#24


0  

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

如果你想要转换成一个“完整”的JS或CSS表示,你可以使用如下的东西:

  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