我有将字符串转换为十六进制的函数:
function encode(str){
str = encodeURIComponent(str).split('%').join('');
return str.toLowerCase();
}
例子:
守护村子
alert(encode('守护村子'));
输出将是:
e5ae88e68aa4e69d91e5ad90
适用于汉字。但是当我用英文字母做的时候
alert(encode('Hello World'))
;
它输出:
hello20world
我试过将字符串转换为十六进制:
function String2Hex(tmp) {
var str = '';
for(var i = 0; i < tmp.length; i++) {
str += tmp[i].charCodeAt(0).toString(16);
}
return str;
}
然后在上面的汉字上试了一下,结果输出的是UTF-8 HEX:
5b8862a467515b50
不是 ANSI 十六进制:
e5ae88e68aa4e69d91e5ad90
我也搜索过将 UFT8 转换为 ANSI,但没有成功。 任何人都可以帮助我吗?谢谢!
作为函数式风格的独立解决方案,您可以使用以下方式进行编码:
plain.split("")
.map(c => c.charCodeAt(0).toString(16).padStart(2, "0"))
.join("");
空字符串上的
split
生成一个数组,每个元素中包含一个字符(或者更确切地说,一个 UTF-16 代码点)。然后我们可以将每个映射到字符代码的十六进制字符串。
然后解码:
hex.split(/(\w\w)/g)
.filter(p => !!p)
.map(c => String.fromCharCode(parseInt(c, 16)))
.join("")
这次传递给
split
的正则表达式捕获两个字符的组,但是这种形式的 split
将用空字符串穿插它们(捕获组“之间”的东西,这没什么!)。所以 filter
用于删除空字符串。然后map
解码每个字符。
在 Node.js 上,您可以:
const myString = "This is my string to be encoded/decoded";
const encoded = Buffer.from(myString).toString('hex'); // encoded == 54686973206973206d7920737472696e6720746f20626520656e636f6465642f6465636f646564
const decoded = Buffer.from(encoded, 'hex').toString(); // decoded == "This is my string to be encoded/decoded"
我通过下载解决了它
utf8.js
https://github.com/mathiasbynens/utf8.js
然后使用上面的
String2Hex
函数:
alert(String2Hex(utf8.encode('守护村子')));
它给了我想要的输出:
e5ae88e68aa4e69d91e5ad90
这应该有效。
var str="some random string";
var result = "";
for (i=0; i<str.length; i++) {
hex = str.charCodeAt(i).toString(16);
result += ("000"+hex).slice(-4);
}
如果你想正确处理 UTF8 字符串,你可以试试这些:
function utf8ToHex(str) {
return Array.from(str).map(c =>
c.charCodeAt(0) < 128
? c.charCodeAt(0).toString(16)
: encodeURIComponent(c).replace(/\%/g,'').toLowerCase()
).join('');
}
function hexToUtf8(hex) {
return decodeURIComponent('%' + hex.match(/.{1,2}/g).join('%'));
}
另一种方法
function toHex(txt){
const encoder = new TextEncoder();
return Array
.from(encoder.encode(txt))
.map(b => b.toString(16).padStart(2, '0'))
.join('')
}