How to convert decimal to hex in JavaScript?
如何在JavaScript中将十进制值转换为十六进制等价值?
Convert a number to a hexadecimal string with:
hexString = yourNumber.toString(16);
and reverse the process with:
yourNumber = parseInt(hexString, 16);
If you need to handle things like bit fields or 32-bit colors, then you need to deal with signed numbers. The javascript function toString(16) will return a negative hex number which is usually not what you want. This function does some crazy addition to make it a positive number.
function decimalToHexString(number)
{
if (number < 0)
{
number = 0xFFFFFFFF + number + 1;
}
return number.toString(16).toUpperCase();
}
The code below will convert the decimal value d to hex. It also allows you to add padding to the hex result. so 0 will become 00 by default.
function decimalToHex(d, padding) {
var hex = Number(d).toString(16);
padding = typeof (padding) === "undefined" || padding === null ? padding = 2 : padding;
while (hex.length < padding) {
hex = "0" + hex;
}
return hex;
}
链接地址: http://www.djcxy.com/p/31766.html
上一篇: 我如何用我的内核创建可启动的CD映像?