lib = {
const hexAlphabet = "0123456789abcdef";
const toByteStr = (a) => String.fromCharCode(...a);
const fromByteStr = (s) => s.split("").map(c => c.charCodeAt(0));
const toHex1 = (x) => {
let hex = x.toString(16);
if (hex.length == 1) { hex = "0" + hex;}
return hex
};
return {
toByteStr, fromByteStr,
atoi: (a) => a.charCodeAt(0),
itoa: (i) => String.fromCharCode(i),
toHex1,
toHex: (s) => s.map(toHex1).join(""),
fromHex: (s) => {
if ((s.length % 2) !== 0) {
throw 'hex string must have length divisible by 2';
}
let ints = [];
for (let i = 0; i < s.length; i += 2) {
let c1 = s[i];
let c2 = s[i+1];
let b = hexAlphabet.indexOf(c2) + (hexAlphabet.indexOf(c1) << 4);
ints.push(b);
}
return ints;
},
tob64: (arr) => btoa(toByteStr(arr)),
fromb64: (s) => fromByteStr(atob(s)),
fromBinArr: (x) => {
let result = 0;
for (let i = 0; i < 8; i += 1) {
result |= x[7 - i] << i
}
return result;
},
toBinArr: (c) => {
if (c > 255) {
throw 'must be 8 bit byte';
}
let result = [];
result[7] = (c & 1) > 0 ? 1 : 0;
result[6] = (c & 2) > 0 ? 1 : 0;
result[5] = (c & 4) > 0 ? 1 : 0;
result[4] = (c & 8) > 0 ? 1 : 0;
result[3] = (c & 16) > 0 ? 1 : 0;
result[2] = (c & 32) > 0 ? 1 : 0;
result[1] = (c & 64) > 0 ? 1 : 0;
result[0] = (c & 128) > 0 ? 1 : 0;
return result;
}
}
}