This post will discuss how to convert a number to a hex string in JavaScript.

To convert a number to a hex string in JavaScript, we can use one of the following functions:

1. Using Number.toString() function

We can use the Number.toString() function of the number object, which takes a base as an argument and returns the string representation of the number in that base. We can pass 16 as the base argument to get the hexadecimal representation of the number. This method works for both positive and negative numbers. For example, we can convert a number to a hex string using toString() like this:

Download  Run Code

 
We can use it with the padStart() function of the string object to add the prefix to the hex string if needed. The padStart() function pads a string with another string until it reaches a certain length. For example, to convert a positive number 100 to a hex string with prefix "0x":

Download  Run Code

 
Alternatively, we can use the + operator to add a prefix to the hex string. For example, we can convert a positive number to a hex string with prefix "0x" using + like this:

Download  Run Code

2. Using bitwise operators

We can use the bitwise operators to manipulate the bits of the number and extract the hex digits. For example, we can use the right shift operator (>>) to divide the number by 16 and get the remainder, which is the last hex digit. Then we can use the bitwise AND operator (&) to mask out the last four bits of the number and repeat the process until we get all the hex digits. We can use a lookup table to map each hex digit to its corresponding character. This method works for both positive and negative numbers. For example:

Download  Run Code

3. Using BigInt object

Another option is to convert the number to the BigInt value, and use the toString() function of the BigInt object with a radix of 16 to convert it to a hexadecimal string. This will handle negative numbers correctly, but it requires a modern browser that supports BigInt. For example:

Download  Run Code

That’s all about converting a number to a hex string in JavaScript.