3

Sometimes from network transmissions/usdb devices you receive the data has a hexadimal string eg:

"12ADFF1345"

These type of string I want somehow to be converted into a binary equivalent into a buffer, in order to perform a some mathematical or binary operations on them.

Do you know how I can achieve that?

2 Answers 2

5

Use the builtin Buffer class :

let buf1 = Buffer.from('12ADFF1345', 'hex');

let value = buf1.readInt32LE(0);
let value2 = buf1.readInt16LE(2);
console.log(value,value2);


>> 335523090 5119
// '13ffad12' '13FF' (LE) 
>> 313392915 -237
// '12ADFF13' 'ff13' (BE)

https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_string_encoding

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

Comments

0

Yes I know how to do that, the algorithm is simple (assuming that you have no escape characters):

  1. Split the read string into a character.
  2. Group each character pair.
  3. Then generate the string 0x^first_character_pair^
  4. parseInt the string above with base 16

In other words consult the following code:

const hexStringToBinaryBuffer = (string) => {
  const subStrings = Array.from(string);
  let previous = null;
  const bytes = [];
  _.each(subStrings, (val) => {
    if (previous === null) { // Converting every 2 chars as binary data
      previous = val;
    } else {
      const value = parseInt(`0x${previous}${val}`, 16);
      bytes.push(value);
      previous = null;
    }
  });

  return Buffer.from(bytes);
};

This is usefull if you pass as string the result of a Buffer.toString('hex') or equivalent method via a network socket or a usb port and the other end received it.

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.