You don’t say what types of data the variables will be - assuming they are always integers without signal, this answer works - by the way, there are no "hexadecimal data" - there are data that are strings of bytes - you have them transformed into a string in which they are represented as a sequence of 2-digit hexadecimal numbers. The functions below assume that your string, on the contrary, contains the bytes themselves as "codepoints" Unicode - if your string actually has hexadecimal data, you will need to convert these numbers into hexa to "numbers" true before - once having a sequence of numbers from 0 to 255, the functions are almost the same:
If you don’t need/don’t want variable names, and your data is in a string and is "big endian", this function solves the problem:
function extract_data(spec, stream) {
var result = new Array;
var index = 0;
for (var i = 0; i < spec.length; i++) {
var size = spec[i];
var item = 0;
for (var j = 0; j < size; j++) {
item <<= 8;
item += stream.codePointAt(index);
index++;
}
result.push(item)
}
return result
}
Where "spec" is just the description of how many bytes each variable has
(again, assuming they are all positive integers, with variable width of bytes) - in your example, spec would be [2, 1, 1, 2, 2, 4]
.
If the data is little-endian, you will need this variant:
function extract_data(spec, stream) {
var result = new Array;
var index = 0;
for (var i = 0; i < spec.length; i++) {
var size = spec[i];
var item = 0;
for (var j = size - 1; j >= 0; j--) {
item <<= 8;
item += stream.codePointAt(index + j);
}
index += size;
result.push(item)
}
return result
}
(the operator y <<= X
makes a shift of X binary digits in the content of the number y - the same as multiplying the number by 2 8 (256): that’s how many times a more significant byte is greater than another when composing whole numbers on the computer).