JS中Bytearray的map方法原理及Buffer转十六进制异常解析
问题分析:toHexString函数未返回预期结果的原因及for循环重写
问题描述
我编写了如下toHexString函数:
function toHexString(bytes) { const a = bytes.map(function (byte) { console.log("--------------------") const parsedValue = ("00" + (byte & 0xFF).toString(16)).slice(-2) console.log(parsedValue) console.log(typeof parsedValue) console.log("--------------------") return ("00" + (byte & 0xFF).toString(16)).slice(-2); }); console.log(a) } toHexString(Buffer.from("2241f2", 'hex'))
执行后日志输出:
-------------------- 22 string -------------------- -------------------- 41 string -------------------- -------------------- f2 string -------------------- <Buffer 16 29 00>
我原本期望得到输出结果"2241f2",但实际并非如此,想知道原因是什么?另外希望用for循环重写该函数帮助理解。
我自己尝试的for循环实现:
const a = Buffer.from("2241f2", 'hex') const b= [] for (let byte of a) { b.push(("00" + (byte & 0xFF).toString(16)).slice(-2)) } console.log(b)
执行结果为:
[ '22', '41', 'f2' ]
原因分析
- 原函数未拼接结果:你的
toHexString函数中,map方法确实将每个字节转换为了两位十六进制字符串,但最后仅打印了转换后的数组,没有将数组元素拼接成完整字符串,因此无法得到预期的"2241f2"。 - Buffer日志为干扰项:日志中的
<Buffer 16 29 00>并非map返回数组的输出,属于无关日志。从map内部的打印可以看到,每个字节的转换结果都是正确的"22"、"41"、"f2",只是缺少拼接步骤。 - 你的for循环差最后一步:你用for循环得到了正确的转换数组
['22', '41', 'f2'],但同样未将数组元素拼接为字符串,只需调用b.join('')即可得到预期结果。
修正后的函数(含for循环版本)
修正原map版本
function toHexString(bytes) { const hexArr = bytes.map(byte => { return ("00" + (byte & 0xFF).toString(16)).slice(-2); }); // 将数组元素拼接为完整十六进制字符串 const hexStr = hexArr.join(''); console.log(hexStr); // 输出 "2241f2" return hexStr; } toHexString(Buffer.from("2241f2", 'hex'));
for循环重写版本
function toHexString(bytes) { const hexArr = []; for (const byte of bytes) { // 单个字节转两位十六进制字符串 const hexByte = ("00" + (byte & 0xFF).toString(16)).slice(-2); hexArr.push(hexByte); } // 拼接为完整字符串 const hexStr = hexArr.join(''); console.log(hexStr); // 输出 "2241f2" return hexStr; } toHexString(Buffer.from("2241f2", 'hex'));
无数组中转的简化for循环版本
如果不需要数组存储中间结果,也可以直接拼接字符串:
function toHexString(bytes) { let hexStr = ''; for (const byte of bytes) { hexStr += ("00" + (byte & 0xFF).toString(16)).slice(-2); } console.log(hexStr); // 输出 "2241f2" return hexStr; } toHexString(Buffer.from("2241f2", 'hex'));
内容的提问来源于stack exchange,提问作者Chau Loi
相关产品推荐
相关产品推荐

