js实现hex解码
Hex 解码的实现方法
Hex 解码是将十六进制字符串转换为原始数据或文本的过程。以下是几种常见的 JavaScript 实现方法:
使用 Buffer(Node.js 环境)
在 Node.js 环境中,可以使用 Buffer 类来实现 Hex 解码:
const hexString = '48656c6c6f20576f726c64'; // "Hello World" 的 Hex 编码
const buffer = Buffer.from(hexString, 'hex');
const decodedText = buffer.toString('utf8');
console.log(decodedText); // 输出: "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"
手动解析 Hex 字符串
如果不依赖环境 API,可以通过手动解析实现:
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
此方法适用于编码后的 Hex 字符串(如 URL 编码):
function hexDecode(hexString) {
return decodeURIComponent(
hexString.replace(/\s+/g, '').replace(/../g, '%$&')
);
}
const hexString = '48656c6c6f20576f726c64';
console.log(hexDecode(hexString)); // 输出: "Hello World"
注意事项
- 输入验证:确保 Hex 字符串长度为偶数,否则需要补零或处理异常。
- 编码格式:明确目标编码(如 UTF-8、ASCII),避免解码后乱码。
- 性能优化:对于大字符串,手动解析可能较慢,建议使用原生 API(如
Buffer或TextDecoder)。







