如何在Javascript中将固定长度的整数转换为十六进制? [英] How can I convert an integer to hex with a fix length in Javascript?
问题描述
我想将 Integer
转换为十六进制字符串
,且在JavaScript中具有固定长度
I want to convert an Integer
to a hex-string
with a fix length in JavaScript
例如,我想将154转换为长度为4位数字的十六进制( 009A
)。我无法找出执行此操作的正确方法。
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.
推荐答案
Number.prototype.toString( )
可以在将 16
作为参数(基数为16)传递时将数字转换为十六进制:
Number.prototype.toString()
can convert a number to hexadecimal when 16
is passed as the argument (base 16):
new Number(154).toString(16) //'9A'
但是,这不会有前导零。如果您希望在前导零之前添加一个字符串,则可以提供一个由4个零组成的字符串'0000'
与'9A'
,然后使用slice抓取最后4个字符:
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
事件的顺序显示如下:
154 -> '9a' -> '9A' -> '00009A' -> '009A'
这篇关于如何在Javascript中将固定长度的整数转换为十六进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!