HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Convert decimal number to hexadecimal

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptdecimalhexadecimalconvertnumber

Problem

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.
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.

Solution

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

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

Code Snippets

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

decimalToHex(0); // '0'
decimalToHex(255); // 'ff'
const hexToDecimal = hex => parseInt(hex, 16);

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

Context

From 30-seconds-of-code: decimal-to-hex

Revisions (0)

No revisions yet.