Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert an integer to hex with a fix length in Javascript?

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.

like image 824
kenzie Avatar asked Feb 21 '17 13:02

kenzie


People also ask

Which method converts an integer to a hexadecimal string?

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.

How do you turn an integer into a string in JavaScript?

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.

How do you convert a number to hexadecimal?

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.

What is the fastest way to convert number to string in JavaScript?

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.


2 Answers

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'
like image 55
hackerrdave Avatar answered Oct 24 '22 09:10

hackerrdave


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);
like image 25
Nina Scholz Avatar answered Oct 24 '22 10:10

Nina Scholz