JavaScript/进制:修订间差异
来自康健生活
| 第49行: | 第49行: | ||
console.log(hexData.toString("utf-8")); | console.log(hexData.toString("utf-8")); | ||
// => N</syntaxhighlight> | // => N</syntaxhighlight> | ||
== 十六进制字符串转整数 == | |||
{{Leftrightflex| | |||
<syntaxhighlight lang="javascript"> | |||
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); | |||
}hex2int('4e00') | |||
</syntaxhighlight>|{{consoleout|<pre> | |||
19968</pre>}}}} | |||
2020年6月22日 (一) 14:39的版本
引言
十进制转十六进制
模板:Leftrightflex 也可以简化写法为 模板:Leftrightflex
function toHex(num){
var rs = "";
var temp;
while(num/16 > 0){
temp = num%16;
rs = (temp+"").replace("10","a").replace("11","b").replace("12","c").replace("13","d").replace("14","e").replace("15","f") + rs;
num = parseInt(num/16);
}
return rs;
}
十六进制转十进制
65535 除 16,余数 15(F),商4095 4095 除 16,余数 15(F),商255 255 除 16,余数 15(F),商15 15 除16,余数 15(F),商0,结束 得16进制为 FFFF 15*Math.pow(16,3)+15*Math.pow(16,2)+15*Math.pow(16,1)+15*Math.pow(16,0);
// 错误示例,没有改完
var num = 0;
'4e00'.replace(/(.)(?=[^$])/g, "$1,").split(",").forEach(function(d, i){
//d.charCodeAt(1).toString(); // 转为二进制
const parseIntD = parseInt(d, 16);
num += parseIntD*Math.pow(16,('4e00'.length - i - 1));
})
十六进制转二进制
注:十六进制字节如果超过13位会出现丢失
十六进制转字符串
var data = '4e00'
var hexData = new Buffer(data,'hex');
console.log(hexData.toString("utf-8"));
// => N
十六进制字符串转整数
No categories