JavaScript 将缓冲区中的十六进制字符串与 Python 进行比较
JavaScript compare hex string from buffer to Python
我想从 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>
您可以通过映射方法将缓冲区转换为数组并将每个项目转换为十六进制字符串。最后使用 \x
(包括前导 '\x')
将数组连接到字符串
肮脏的例子
let str = '\x' +
[0xd3, 0xe9, 0x52, 0x18, 0x4c, 0xe7, 0x77, 0xf7, 0xd7]
.map(item => item.toString(16))
.join('\x');
console.log(str); // \xd3\xe9\x52\x18\x4c\xe7\x77\xf7\xd7
或者,您可以将 toString('hex') 字符串拆分为两个字符块(数组),然后将其与 \x
连接(包括前导 \x
,如上)喜欢:
let str = 'd3e952184ce777f7d7';
str = '\x' + str.match(/.{1,2}/g).join('\x');
console.log(str); // \xd3\xe9\x52\x18\x4c\xe7\x77\xf7\xd7
这似乎符合您的要求:
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(''));
您基本上想要区分输出中的可打印字符和 non-printable ASCII 字符。
我想从 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>
您可以通过映射方法将缓冲区转换为数组并将每个项目转换为十六进制字符串。最后使用 \x
(包括前导 '\x')
肮脏的例子
let str = '\x' +
[0xd3, 0xe9, 0x52, 0x18, 0x4c, 0xe7, 0x77, 0xf7, 0xd7]
.map(item => item.toString(16))
.join('\x');
console.log(str); // \xd3\xe9\x52\x18\x4c\xe7\x77\xf7\xd7
或者,您可以将 toString('hex') 字符串拆分为两个字符块(数组),然后将其与 \x
连接(包括前导 \x
,如上)喜欢:
let str = 'd3e952184ce777f7d7';
str = '\x' + str.match(/.{1,2}/g).join('\x');
console.log(str); // \xd3\xe9\x52\x18\x4c\xe7\x77\xf7\xd7
这似乎符合您的要求:
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(''));
您基本上想要区分输出中的可打印字符和 non-printable ASCII 字符。