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

佐手、 提交于 2019-12-05 09:04:41

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!