I want to convert an Integer
to a hex-string
with a fix length in JavaScript
For example I want to convert 154 to hex with a length of 4 digits (009A
). I can't figure out a proper way to do that.
toHexString() method in Java converts Integer to hex string. Let's say the following are our integer values. int val1 = 5; int val2 = 7; int val3 = 13; Convert the above int values to hex string.
The toString() method in Javascript is used with a number and converts the number to a string. It is used to return a string representing the specified Number object. The toString() method is used with a number num as shown in the above syntax using the '. ' operator.
Go through the steps given below to learn how to convert the numbers from decimal to hex. Step 1: First, divide the decimal number by 16, considering the number as an integer. Step 2: Keep aside the remainder. Step 3: Again divide the quotient by 16 and repeat till you get the quotient value equal to zero.
Adding empty string to the number value will convert the data to string is one of the simplest way to do the job. It is also considered to be faster than the above two when it comes to performance.
Number.prototype.toString()
can convert a number to hexadecimal when 16
is passed as the argument (base 16):
new Number(154).toString(16) //'9A'
However, this will not have leading zeroes. If you wish to prepend the leading zeroes you can provide a string of 4 zeroes '0000'
to concatenate with '9A'
, then use slice to grab just the last 4 characters:
var value = 154;
var hex = ('0000' + value.toString(16).toUpperCase()).slice(-4); //009A
The sequence of events is displayed like this:
154 -> '9a' -> '9A' -> '00009A' -> '009A'
You could add some zeroes and use String#slice
for the stringed number.
var value = 154,
string = ('0000' + value.toString(16).toUpperCase()).slice(-4);
console.log(string);
With String#padStart
var value = 154,
string = value.toString(16).toUpperCase().padStart(4, 0);
console.log(string);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With