我想从 Buffer
打印十六进制转义序列字符串。
例如:
buffer = .... // => <Buffer d3 e9 52 18 4c e7 77 f7 d7>
如果我这样做:
console.log(buffer.toString('hex'));
我得到:
d3e952184ce777f7d7
但我想要这个表示与 \x
表示(我从 python 中获取并需要比较)
\xd3\xe9R\x18L\xe7w\xf7\xd7` // same as <Buffer d3 e9 52 18 4c e7 77 f7 d7>
最佳答案
这似乎可以满足您的要求:
function encodehex (val) {
if ((32 <= val) && (val <= 126))
return String.fromCharCode(val);
else
return "\\x"+val.toString(16);
}
let buffer = [0xd3, 0xe9, 0x52, 0x18, 0x4c, 0xe7, 0x77, 0xf7, 0xd7];
console.log(buffer.map(encodehex).join(''));
您基本上想要区分输出中的可打印和不可打印的 ASCII 字符。
关于JavaScript 将缓冲区中的十六进制字符串与 Python 进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49239324/