【发布时间】:2020-06-15 16:47:07
【问题描述】:
在我的客户端/服务器应用程序中,我从服务器获取十六进制格式的字符串,我需要将其转换为 UTF8。然后经过一些操作,我需要将字符串编码回来,从 UTF8 到 Hex 并返回到服务器。
我已经构建了这个函数来将十六进制字符串解析为 UTF8。但是,当我尝试反转这个算法时,我得到了完全不同的东西。
这是我的测试:
function hexToUtf8(s)
{
return decodeURIComponent(
s.replace(/\s+/g, '') // remove spaces
.replace(/[0-9a-f]{2}/g, '%$&') // add '%' before each 2 characters
);
}
function utf8ToHex(s)
{
return encodeURIComponent(s).replace(/%/g, ""); // remove all '%' characters
}
var hex = "52656c6179204f4e214f706572617465642062792030353232";
var utf8 = hexToUtf8(hex); // result: "Relay ON!Operated by 0522" (correct value)
var hex2 = utf8ToHex(utf8); // result: "Relay20ON!Operated20by200522" (some junk)
console.log("Hex: " + hex);
console.log("UTF8: " + utf8);
console.log("Hex2: " + hex2);
console.log("Is conversion OK: " + (hex == hex2)); // false
【问题讨论】:
-
我给你做了一个sn-p来拥有minimal reproducible example
-
你似乎忘记了 hex2 中的空格
-
encodeURIComponent不是 HEX,你确定是 HEX 吗? -
@Keith - 我确定我想得到十六进制的结果,我不确定我需要使用
encodeURIComponent
标签: javascript encoding utf-8 hex