简体   繁体   English

JavaScript比较缓冲区和Python之间的十六进制字符串

[英]JavaScript compare hex string from buffer to Python

I want to print a hex escaped sequence string from a Buffer . 我想从Buffer打印一个十六进制的转义序列字符串。

for instance: 例如:

buffer = .... // => <Buffer d3 e9 52 18 4c e7 77 f7 d7>

if I do: 如果我做:

console.log(buffer.toString('hex'));

I get: 我得到:

d3e952184ce777f7d7

but I want this representation with the \\x representations (I get get from python and need to compare) 但我想使用\\x表示形式来表示(我从python获取并需要进行比较)

\xd3\xe9R\x18L\xe7w\xf7\xd7` // same as <Buffer d3 e9 52 18 4c e7 77 f7 d7>

This seems to do what you want: 这似乎可以满足您的要求:

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(''));

You basically want to differentiate between printable and non-printable ASCII characters in the output. 基本上,您要在输出中区分可打印和不可打印的ASCII字符。

You could convert the buffer to array and each item to hex string by the map method. 您可以通过map方法将缓冲区转换为数组,将每个项目转换为十六进制字符串。 Finally join the array to string with \\x (incl. leading '\\x') 最后使用\\x将数组连接到字符串(包括前导'\\ x')

dirty example 肮脏的例子

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

Alternatively you can split your toString('hex') string into two character chunks (array) and join it with \\\\x (incl. leading \\\\x as above) Like: 或者您可以将您的toString(“十六进制”)字符串分割成两个字符块(阵列),并加入它\\\\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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM