问题
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.
回答1:
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'
回答2:
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);
来源:https://stackoverflow.com/questions/42368797/how-can-i-convert-an-integer-to-hex-with-a-fix-length-in-javascript