1

I am using node.js v6.

I have this hex string;

let hex_string = "0102030402";

I would like to convert hex_string into an array of integer array_hex_integer that looks like this;

let array_hex_integer;
array_hex_integer = [1, 2, 3, 4, 2];

The first element in array_hex_integer corresponds to '01' (1st and 2nd chars) in hex_string, 2nd element corresponds to '02' (3rd and 4th chars) in hex_string and so on.

1
  • good luck with that Commented Nov 16, 2016 at 2:31

3 Answers 3

7

Here is one possible way to do what you need.

var hex_string = "0102030402";
var tokens = hex_string.match(/[0-9a-z]{2}/gi);  // splits the string into segments of two including a remainder => {1,2}
var result = tokens.map(t => parseInt(t, 16));

See: https://stackblitz.com/edit/js-hozzsn?file=index.js

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

2 Comments

Upvoted. Although my answer was selected as the answer, I think your answer is much better than my long-winded answer. Brilliant :)
Upvoted as well, although it does not work completely yet with real hexa: 1) the regexp should be /../g or /[0-9a-z]{2}/gi, 2) and parseInt(t, 16) should specify the radix.
2

In javascript I use this function to convert hexstring to unsigned int array

function hexToUnsignedInt(inputStr) {
  var hex  = inputStr.toString();
  var Uint8Array = new Array();
  for (var n = 0; n < hex.length; n += 2) {
    Uint8Array.push(parseInt(hex.substr(n, 2), 16));
  }
  return Uint8Array;
}

Hope this helps someone

Comments

0

First, split hex_string into an array of string. See my function split_str(). Then, convert this array of string into the array of integer that you want.

function split_str(str, n)
{
    var arr = new Array;
    for (var i = 0; i < str.length; i += n)
    {
        arr.push(str.substr(i, n));
    }
    return arr;
}

function convert_str_into_int_arr(array_str)
{
    let int_arr = [];
    for (let i =0; i < array_str.length; i++)
    {
        int_arr [i]=parseFloat(array_str[i]);
    }

    return int_arr;
}

let answer_str = split_str(hex_string,10);
let answer_int = convert_str_into_int_arr(answer_str);

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.