. Advertisement .
..3..
. Advertisement .
..4..
Have you ever run into the converting task with a given number? This tutorial focuses on discussing the best approach to convert number to hexadecimal in Javascript.
How To Convert Number To Hexadecimal In Javascript
Method 1: Use The toString() function
Before converting a number to a hexadecimal, you need to distinguish clearly between a decimal and hexadecimal number. The decimal system contains ten digits from 0 to 9. In this number system, the value will represent 0,1,2,3,4,5,6,7,8 and 9. 10 is the base in this case.
The hexadecimal system comes with 16 alphanumeric values, ranging from 0 to 9 and alphabetically A to F. The value represents 0,1,2,3,4,5,6,7,8, and 9, A, B, C, D, E, and F correspondingly. Here, the system base is 16 with 16 alphanumeric values.
Using the toString() function is one of the easiest and quickest ways to convert a number to hexadecimal in Javascript. The function shows the decimalNumber.toString( radix ) syntax.
It accepts two following parameters, which are the base of a converted string. The decimalNumber parameter is used to keep your given number in a decimal format. This needs to be converted later one.
The base parameter keeps the number system’s base, in which you will execute a command to convert a number. In this case, the base will be 16 to accomplish the task.
The optional radix parameter is employed to specify the base to represent numeric values. It should be an integer valuing from 2 through 36.
Example:
function decToHex(num){
return num.toString(16)
}
console.log(decToHex(15));
Output:
f
In this example, a dexToHex() function is created. Its input is a num decimal number. The toString() option will likely convert a decimal into a hexadecimal one.
The code will pass the base 16. Finally, you will receive a hexadecimal number with the printed result. The final coding line passes an input of the 15 decimal number to decToHex() option.
The returned hex number is f because it is the 15 number in hexadecimal. The function allows users to modify the output with a F uppercase. This can be done with the toUpperCase() option.
function decToHex(num){
return num.toString(16).toUpperCase()
}
console.log(decToHex(15));
Output:
F
Other Approaches
Integer.toHexString() and Integer.parseInt() options are other alternatives to convert a number to hexadecimal. The first one will represent a string of the integer with an argument of an unsigned integer. It will operate in base 16.
The latter option enables users to set the optional radix for a hexadecimal set as 16.
Conclusion
You will need to convert a number to hexadecimal to solve your coding problem. In this case, the toString() method will be a brilliant choice. With two parameters as the converted string’s base, there should be no difficulty in the converting task.
Leave a comment