30秒学会 JavaScript 片段 · 2022年8月5日

30秒学会 JavaScript 片段 – Convert decimal number to hexadecimal

Numeric values are represented in decimal format by default, when converted to strings. If you want to display them in hexadecimal format, you can use Number.prototype.toString() and pass the base you want to use (16) as an argument.

代码实现

const decimalToHex = dec => dec.toString(16);

decimalToHex(0); // '0'
decimalToHex(255); // 'ff'

Conversely, the opposite might also be needed. You can use parseInt() to convert a string to a number in a given base. If you don’t specify a base, it will default to 10.

使用样例

const hexToDecimal = hex => parseInt(hex, 16);

hexToDecimal('0'); // 0
hexToDecimal('ff'); // 255

翻译自:https://www.30secondsofcode.org/js/s/decimal-to-hex