将字符串编码为十六进制 [英] Encode String to HEX
问题描述
我有将字符串转换为十六进制的功能:
i have my function to convert string to hex:
function encode(str){
str = encodeURIComponent(str).split('%').join('');
return str.toLowerCase();
}
示例:
守护村子
alert(encode('守护村子'));
输出为:
e5ae88e68aa4e69d91e5ad90
它适用于汉字.但是当我用英文字母
It works on Chinese characters. But when i do it with English letters
alert(encode('Hello World'))
;
它输出:
hello20world
我已经尝试过将字符串转换为十六进制:
I have tried this for converting string to hex:
function String2Hex(tmp) {
var str = '';
for(var i = 0; i < tmp.length; i++) {
str += tmp[i].charCodeAt(0).toString(16);
}
return str;
}
然后在上面的中文字符上进行了尝试,但是它输出的是UTF-8十六进制:
then tried it on the Chinese characters above, but it outputs the UTF-8 HEX:
5b8862a467515b50
不是ANSI十六进制:
not the ANSI Hex:
e5ae88e68aa4e69d91e5ad90
我也搜索过将UFT8转换为ANSI,但是没有运气. 有人可以帮助我吗?谢谢!
I also have searched converting UFT8 to ANSI but no luck. Anyone could help me? Thanks!
推荐答案
我已经通过下载utf8.js
https://github.com/mathiasbynens/utf8.js
然后使用上面的String2Hex
函数:
alert(String2Hex(utf8.encode('守护村子')))
;
给我我想要的输出:
e5ae88e68aa4e69d91e5ad90
这篇关于将字符串编码为十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!