4

How can I format a hex to be displayed always with 4 digits in javascript?

For example, I converting a decimal to hex :

port = 23
function d2h(d) {return (+d).toString(16);}
d2h(port)

I am successfully able to convert "23" to the hex value "17". However, I would like to be formatted like this "0017" (with four digits -- appending 0's before the 17).

All information would be greatly appreciated.

4

2 回答 2

12

这是一个简单的方法:

return ("0000" + (+d).toString(16)).substr(-4);

或者:

return ("0000" + (+d).toString(16)).slice(-4);
于 2013-10-15T17:37:22.313 回答
0

您可以使用 sprintf http://www.diveintojavascript.com/projects/javascript-sprintf

我还没有尝试过,但是这样的东西应该可以工作:

sprintf("%.4X", d)
于 2013-10-15T17:36:26.987 回答