JavaScript-将UTF8编码/解码为Hex,将Hex编码为UTF8

问题描述 投票:0回答:1

在我的客户端/服务器应用程序中,我从服务器获取十六进制格式的字符串,我需要将其转换为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
javascript encoding utf-8 hex
1个回答
1
投票

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

因此,我对您的utf8toHex进行了稍微修改,以处理十六进制。

更新忘了toString(16)不会将十六进制预先清零,因此如果值小于16,例如。换行等会失败因此,添加0并进行切片以确保。

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)
{
  let r = '';
  for (let l = 0; l < s.length; l += 1)
    r += ('0' + s.charCodeAt(l).toString(16)).slice(-2);
  return r;
}


var hex = "52656c6179204f4e214f706572617465642062792030353232";

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

0
投票

您可以简化编码/解码:

const encode = str => Buffer.from(str).toString('hex');
const decode = str => Buffer.from(str, 'hex').toString();

const text = "String to encode";
const encoded = encode(text);
const decoded = decode(encoded);

console.log({text, encoded, decoded})
© www.soinside.com 2019 - 2024. All rights reserved.