How to convert decimal to hexadecimal in JavaScript
The quickest method to convert a decimal to hexadecimal in JavaScript is using the toString()
method with the argument of 16, which represents hexadecimal:
In reverse, use parseInt()
with a 16 radix argument to convert hexadecimal back to decimal:
Encapsulating it in a function makes it more reusable:
Even negative numbers can be converted to two's complement hexadecimal:
And let's not forget about the style, if you want your hexadecimal characters to scream, make them uppercase:
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:
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:
Was this article helpful?