admin管理员组文章数量:1432309
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.
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.
- good luck with that – Software Engineer Commented Nov 16, 2016 at 2:31
3 Answers
Reset to default 6Here 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./edit/js-hozzsn?file=index.js
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
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);
本文标签: Convert this hex string into array of integer in javascriptStack Overflow
版权声明:本文标题:Convert this hex string into array of integer in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744582801a2614024.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论