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

我怕爱的太早我们不能终老 提交于 2019-12-07 06:49:34

问题


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

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