1

I am getting a Buffer array back in a JSON object when I call one of my API endpoints. I would like to convert this array to a more "usable" form (hex?) so I can compare them, etc. Here is what the object currently looks like:

"hash": {
  "type": "Buffer",
  "data": [
    151,
    14,
    51,
    26,
    46,
    52,
    5,
    151,
    99,
    107,
    38,
    188,
    138,
    180,
    76,
    56,
    108,
    214,
    135,
    213,
    125,
    134,
    105,
    139,
    129,
    236,
    206,
    157,
    67,
    1,
    12,
    12
  ]
}

How would I go about converting this array to a hex (or string, etc.) so that I can compare hashes?

0

3 Answers 3

2

You can just create a new buffer and convert it into the format you need.

var o = {"hash": {
"type": "Buffer",
"data": [
  151,
  14,
  51,
  26,
  46,
  52,
  5,
  151,
  99,
  107,
  38,
  188,
  138,
  180,
  76,
  56,
  108,
  214,
  135,
  213,
  125,
  134,
  105,
  139,
  129,
  236,
  206,
  157,
  67,
  1,
  12,
  12
  ]
 }
}

console.log(new Buffer(o.hash,'hex').toString('hex'));
// 970e331a2e340597636b26bc8ab44c386cd687d57d86698b81ecce9d43010c0c
Sign up to request clarification or add additional context in comments.

Comments

2

If you have an existing Buffer object, you can represent it as hex via:

myBuffer.toString('hex')
// '970e331a2e340597636b26bc8ab44c386cd687d57d86698b81ecce9d43010c0c'

Comments

0

Use Number.prototype.toString:

var json = '{"hash": {"type": "Buffer","data": [151,14,51]}}';
var parsed = JSON.parse(json);
document.write("data: " + JSON.stringify(parsed.hash.data) + "<br>");
document.write("hex: ");
parsed.hash.data.forEach(function(b) { document.write(("00" + b.toString(16)).substr(-2)); });

Comments

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.