Explain Codes LogoExplain Codes Logo

How to convert decimal to hexadecimal in JavaScript

javascript
promises
callbacks
best-practices
Alex KataevbyAlex Kataev·Oct 25, 2024
TLDR

The quickest method to convert a decimal to hexadecimal in JavaScript is using the toString() method with the argument of 16, which represents hexadecimal:

let hex = (255).toString(16); // result is: "ff"; 255 says: "finally famous"

In reverse, use parseInt() with a 16 radix argument to convert hexadecimal back to decimal:

let decimal = parseInt("ff", 16); // returns: 255; "ff" says: "falling flat"

Encapsulating it in a function makes it more reusable:

function decimalToHex(num) { return num.toString(16); } console.log(decimalToHex(255)); // "ff"

Even negative numbers can be converted to two's complement hexadecimal:

function negativeDecimalToHex(num) { return (num >>> 0).toString(16); } console.log(negativeDecimalToHex(-1)); // "ffffffff"; -1 says: "feel free to find fun facts"

And let's not forget about the style, if you want your hexadecimal characters to scream, make them uppercase:

let upperHex = (255).toString(16).toUpperCase(); // "FF"; 255 says: "feel free"

How about non-integers and padding?

Now, you may face a hitch when dealing with non-integers like 48.6 . Well, these troublemakers cannot be converted directly to hexadecimal. Handle their integer parts only or convert fractional parts into their own decimals.

And when you need your hexadecimal output to be of a certain length, padding is your lifesaver:

function toPaddedHexString(num, length) { let hex = num.toString(16); // Time to do some weight lifting 💪 while (hex.length < length) { hex = "0" + hex; } return hex; } console.log(toPaddedHexString(15, 2)); // "0f"; 15 says: "Oh, finally"

Mind the large numbers and bit limits

Remember that JavaScript can accurately handle integers up to 2^53 - 1. Anything beyond that would make JavaScript sweat. Consider libraries like BigInt for extra large figures.

Please, bear in mind that JavaScript treats numbers as 32-bit integers when it comes to bitwise operations, which is critical for maneuvers like the unsigned right shift (>>>).

Best practices for utility functions

Creating utility functions becomes smoother when you follow some best practices such as naming the function descriptively, handling errors elegantly, and catering for edge cases:

function safeDecimalToHex(num) { // Safety goggles on 👓 if (!Number.isInteger(num)) { throw new Error("Sorry, must be an integer. I accept no 'half measures'. "); } // Smooth criminal conversion from decimal to hexadecimal let hex = (num >>> 0).toString(16); // Handling single-digit hexadecimal for numbers under 16 return num < 16 ? '0' + hex : hex; }