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>
1
  • 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... Commented Mar 12, 2018 at 16:14

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Note that doesn't match the supplied desired output.
I ignored the weird letters (R, L, w, ...) ^^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.