【问题标题】:JavaScript - Encode/Decode UTF8 to Hex and Hex to UTF8JavaScript - 将 UTF8 编码/解码为十六进制和十六进制为 UTF8
【发布时间】: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


【解决方案1】:

您的 utf8toHex 正在使用 encodeURIComponent,这不会使所有内容都变为 HEX。

所以我稍微修改了你的 utf8toHex 来处理 HEX。

更新 Forgot toString(16) 不会将十六进制预置零,所以如果它们是 值小于 16,例如。换行等它会失败 因此,要添加 0 并切片以确保。

更新 2, 使用 TextEncoder,这将比使用 charCodeAt 更好地处理 UTF-8。

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));

【讨论】:

  • 在我的应用中实现此代码后,我发现它不起作用。该问题出现在外语中,其中函数charCodeAt() 返回一个包含3 个或更多字符的值。例如,如果hex = 'd7a4' 将等于 UTF 中的 'פ'。然后回到十六进制你会得到5e4 等于d7a4
  • 这是因为 charCodeAt() 返回 UTF-16 而不是 UTF-8 的值。见developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • @GilEpshtain 是的,UTF8 双宽度字符将是一个问题,我会看看我能不能在这里敲出一些更健壮的东西。
  • @GilEpshtain 更新以使用 TextEncoder,因为这确实应该是处理 UTF8 的正确方法,您也可以使用 TextDecoder 但使用 decodeURIComponent 作为简单的 HEX 解码器似乎很好。
猜你喜欢
  • 2017-09-06
  • 1970-01-01
  • 2013-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-02
  • 2019-01-01
  • 1970-01-01
相关资源
最近更新 更多