How to convert decimal to hexadecimal in JavaScript

后端 未结 27 2665
臣服心动
臣服心动 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'
    

提交回复
热议问题