js实现hex解码
Hex 解码的实现方法
Hex 解码是将十六进制字符串转换为原始数据的过程。以下是几种在 JavaScript 中实现 Hex 解码的方法:
使用 Buffer(Node.js 环境)
在 Node.js 环境中,可以使用 Buffer 类直接解码十六进制字符串:

const hexString = '48656c6c6f20576f726c64'; // "Hello World" 的 Hex 编码
const buffer = Buffer.from(hexString, 'hex');
const decodedString = buffer.toString('utf8');
console.log(decodedString); // 输出: "Hello World"
使用 TextDecoder(浏览器环境)
在浏览器中,可以通过 TextDecoder 和 Uint8Array 实现 Hex 解码:

function hexDecode(hexString) {
const bytes = new Uint8Array(hexString.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
return new TextDecoder().decode(bytes);
}
const hexString = '48656c6c6f20576f726c64';
console.log(hexDecode(hexString)); // 输出: "Hello World"
手动转换(通用方法)
以下是一个通用的手动转换方法,适用于任何 JavaScript 环境:
function hexDecode(hexString) {
let str = '';
for (let i = 0; i < hexString.length; i += 2) {
const byte = parseInt(hexString.substr(i, 2), 16);
str += String.fromCharCode(byte);
}
return str;
}
const hexString = '48656c6c6f20576f726c64';
console.log(hexDecode(hexString)); // 输出: "Hello World"
使用 decodeURIComponent 和 escape
另一种方法是结合 decodeURIComponent 和 escape,但需要注意兼容性问题:
function hexDecode(hexString) {
return decodeURIComponent(escape(hexString.replace(/\s+/g, '').replace(/../g, '%$&')));
}
const hexString = '48656c6c6f20576f726c64';
console.log(hexDecode(hexString)); // 输出: "Hello World"
注意事项
- 确保输入的 Hex 字符串是有效的,长度应为偶数。
- 如果 Hex 字符串包含非十六进制字符(如空格或其他符号),需要先进行清理。
- 在浏览器环境中,
Buffer不可用,需使用其他方法。
以上方法可以根据具体需求选择使用。






