Reputation: 28030
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.
Upvotes: 0
Views: 3666
Reputation: 1114
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
Upvotes: 6
Reputation: 654
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
Upvotes: 2
Reputation: 28030
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);
Upvotes: 0