简体   繁体   中英

JavaScript compare hex string from buffer to Python

I want to print a hex escaped sequence string from a 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)

\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.

You could convert the buffer to array and each item to hex string by the map method. Finally join the array to string with \\x (incl. leading '\\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:

let str = 'd3e952184ce777f7d7';
str = '\\x' + str.match(/.{1,2}/g).join('\\x');
console.log(str); // \xd3\xe9\x52\x18\x4c\xe7\x77\xf7\xd7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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