How to convert decimal to hexadecimal in JavaScript

后端 未结 27 2663
臣服心动
臣服心动 2020-11-21 23:05

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

27条回答
  •  走了就别回头了
    2020-11-21 23:48

    In case you're looking to convert to a 'full' JavaScript 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
    

提交回复
热议问题