0

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>
Jared Smith
  • 19,721
  • 5
  • 45
  • 83
Avba
  • 14,822
  • 20
  • 92
  • 192
  • What's up with the extra characters in the Python sample (e.g. R, L, w)? Can you add how that desired output is being generated? That's bigger than a python MAX_INT for example... – Jared Smith Mar 12 '18 at 16:14

2 Answers2

1

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.

0x01
  • 468
  • 2
  • 9
0

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
Domske
  • 4,795
  • 2
  • 20
  • 35