You do not say what data types are variables - assuming they are always unsigned integers, this answer works - by the way, there are no "data in hex" - there are data that are sequences 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, instead, contains the bytes themselves as unicode "codepoints" - if your string actually has the hexadecimal data, you will need to convert those hex numbers to true "numbers" before - one having a sequence of numbers from 0 to 255, the functions are almost the same:
If you do not need / do not want variable names, and if your data is in a string and are " 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 precisely the description of how many bytes each variable has
(again, assuming they are all positive integers with variable byte widths) - 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 y <<= X
operator shifts X binary digits into the contents of the y number - the same as multiplying the number by 2 ^ 8 (256): that is how many times a more significant byte is greater than another in compose whole numbers on the computer).