How to convert decimal to hexadecimal in JavaScript

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

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

27条回答
  •  [愿得一人]
    2020-11-21 23:35

    As the accepted answer states, the easiest way to convert from decimal to hexadecimal 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.

提交回复
热议问题