3

I am using node.js.

I have this string msg_str with the following contents "0102ab00aabb00". I want to convert this string content (ASCII representing binary hex) and store it into a Buffer such that the contents of the Buffer looks like <01 02 ab 00 aa bb 00 >.

Some preliminary code I wrote which does not work as expected;

msg_str = "0102ab00aabb00";
buffer_binary = new Buffer(msg_str);
console.log(msg_str);   
console.log(buffer_binary); 

The console output of buffer_binary is 30 31 30 32 61 62 30 30 61 61 62 62 30 30. The correct output should be 01 02 ab 00 aa bb 00.

1

1 Answer 1

9

You need to tell the Buffer constructor that your string is in hex. Fortunately, this is pretty easy :)

msg_str = "0102ab00aabb00";
buffer_binary = new Buffer(msg_str, "hex"); // specify hex
console.log(msg_str); // logs 0102ab00aabb00
console.log(buffer_binary); // logs <Buffer 01 02 ab 00 aa bb 00>
Sign up to request clarification or add additional context in comments.

1 Comment

is there a way to do this in the browser?

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.