I try to extract the byte values from a string containing hexadecimal byte representations. The string also contains (unknown) non-hexadecimal characters which needs to be ignored (delimiters, whitespace formatting).
Given an input string "f5 df 45:f8 a 8 f53"
, the result would be the array [245, 223, 69, 248, 168, 245]
. Note that byte values are only output from two hexadecimal digits (hence, the last 3
is ignored).
As an additional constraint, the code needs to work in ecmascript 3 environments.
So far, I have used this approach:
function parseHex(hex){
hex = hex.replace(/[^0-9a-fA-F]/g, '');
var i,
len = hex.length,
bin = [];
for(i = 0; i < len - 1; i += 2){
bin.push(+('0x' + hex.substring(i, i + 2)));
}
return bin;
}
However, I feel that it would be possible to find a more elegant solution to this, so the question is:
Is there a better solution to this problem (that would perform better or solve the problem with less code)?