16进制的字符串 转换为整数

function hex2int(hex) {
    var len = hex.length, a = new Array(len), code;
    for (var i = 0; i < len; i++) {
        code = hex.charCodeAt(i);
        if (48<=code && code < 58) {
            code -= 48;
        } else {
            code = (code & 0xdf) - 65 + 10;
        }
        a[i] = code;
    }
    
    return a.reduce(function(acc, c) {
        acc = 16 * acc + c;
        return acc;
    }, 0);
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

 // 15 + 16 * 13 + 256 = 479
console.log(hex2int("1df"));

十进制整数转换16进制

function int2hex(num, width) {
    var hex = "0123456789abcdef";
    var s = "";
    while (num) {
	s = hex.charAt(num % 16) + s;
	num = Math.floor(num / 16);
    }
    if (typeof width === "undefined" || width <= s.length) {
	return "0x" + s;
    }
    var delta = width - s.length;
    var padding = "";
    while(delta-- > 0) {
	padding += "0";
    }
    return "0x" + padding + s;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

console.log(int2hex(479, 8));

0x000001df