JSFiddle - React, Tailwind, and code Playground
HTML
<p>
Type your custom hex data separated by spaces and press 'enter' to see bew result:
</p>
<input type="text" id="input" value="FE AA 02 80 00 2A FD AA 03 80 00 2A 22 F7 AA"><br>
<pre id="result"></pre>
JavaScript
var input = document.getElementById('input'),
result = document.getElementById('result');
/**
* Helper functions to create readable input and output
*/
function str2hex (str) {
return str.split('').map(function (char) {
var value = char.charCodeAt(0);
return ((value < 16 ? '0' : '') + value.toString(16)).toUpperCase();
}).join(' ');
}
function hex2str (hex) {
return hex.split(' ').map(function (string) {
return String.fromCharCode(parseInt(string, 16));
}).join('');
}
/**
* PackBits pack function
*
* @param {String} data
* @return {String}
*/
function packBits (data) {
var output = '',
i = 0;
while (i < data.length) {
var hex = data.charCodeAt(i);
if(hex == 128) {
// do nothing
}
else if (hex > 128) {
// Repeated bytes
hex = 256 - hex;
for (var j = 0; j <= hex; j ++) {
output += data.charAt(i + 1);
}
i ++;
}
else {
// Literal bytes
for (var j = 0; j <= hex; j ++) {
output += data.charAt(i + j + 1);
}
i += j;
}
i ++;
}
return output;
}
function compile () {
console.log(input.value);
result.innerHTML = str2hex(packBits(hex2str(input.value)));
}
compile();
input.addEventListener('change', compile);