How to convert decimal to hexadecimal in JavaScript

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

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

相关标签:
27条回答
  • 2020-11-21 23:51

    Here's a trimmed down ECMAScript 6 version:

    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'
    
    0 讨论(0)
  • 2020-11-21 23:52

    Constrained/padded to a set number of characters:

    function decimalToHex(decimal, chars) {
        return (decimal + Math.pow(16, chars)).toString(16).slice(-chars).toUpperCase();
    }
    
    0 讨论(0)
  • 2020-11-21 23:53

    If you are looking for converting Large integers i.e. Numbers greater than Number.MAX_SAFE_INTEGER -- 9007199254740991, then you can use the following code

    const hugeNumber = "9007199254740991873839" // Make sure its in String
    const hexOfHugeNumber = BigInt(hugeNumber).toString(16);
    console.log(hexOfHugeNumber)

    0 讨论(0)
提交回复
热议问题