user91579631 user91579631 - 21 days ago 7
Javascript Question

Convert this hex string into array of integer in javascript

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.

Answer

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);