gpt4 book ai didi

JavaScript - 将 UTF8 编码/解码为十六进制以及十六进制为 UTF8

转载 作者:行者123 更新时间:2023-12-01 00:04:04 31 4
gpt4 key购买 nike

在我的客户端/服务器应用程序中,我从服务器获取十六进制格式的字符串,我需要将其转换为 UTF8。然后,经过一些操作后,我需要将字符串从 UTF8 编码回十六进制,然后返回到服务器。

我构建了这个函数来将十六进制字符串解析为 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

最佳答案

您的utf8toHex正在使用encodeURIComponent,这不会使所有内容都变成十六进制。

所以我稍微修改了你的 utf8toHex 以处理十六进制。

UpdateForgot toString(16) does not pre-zero the hex, so if they wasvalues less 16, eg. line feeds etc it would failSo, to added the 0 and sliced to make sure.

Update 2,Use TextEncoder, this will handle UTF-8 much better than use charCodeAt.

function hexToUtf8(s)
{
return decodeURIComponent(
s.replace(/\s+/g, '') // remove spaces
.replace(/[0-9a-f]{2}/g, '%$&') // add '%' before each 2 characters
);
}

const utf8encoder = new TextEncoder();

function utf8ToHex(s)
{
const rb = utf8encoder.encode(s);
let r = '';
for (const b of rb) {
r += ('0' + b.toString(16)).slice(-2);
}
return r;
}


var hex = "d7a452656c6179204f4e214f706572617465642062792030353232";

var utf8 = hexToUtf8(hex);
var hex2 = utf8ToHex(utf8);

console.log("Hex: " + hex);
console.log("UTF8: " + utf8);
console.log("Hex2: " + hex2);
console.log("Is conversion OK: " + (hex == hex2));

关于JavaScript - 将 UTF8 编码/解码为十六进制以及十六进制为 UTF8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60504945/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com