Skip to content

Instantly share code, notes, and snippets.

@chaosmonster
Last active January 9, 2021 16:25
Show Gist options
  • Save chaosmonster/1b1cb89e6aae6fc35a89cd1701bced9c to your computer and use it in GitHub Desktop.
Save chaosmonster/1b1cb89e6aae6fc35a89cd1701bced9c to your computer and use it in GitHub Desktop.
function booleanArrayToHex(arr) {
const binaryString = arr.map(it => it ? '1' : '0').join('');
return parseInt(binaryString, 2).toString(16).toUpperCase();
}
function hexToBooleanArray(hex, arrayLength = 16){
const binaryString = (parseInt(hex, 16).toString(2)).padStart(arrayLength, '0');
return binaryString.split('').map(it => it === '1');
}
function randomTest() {
const rndLength = Math.floor(Math.random() * 20) + 1;
const testArr = [];
for (let i = 0; i < rndLength; i++) {
testArr.push((Math.floor(Math.random() * 20) + 1)%2 === 0);
}
console.log('test array', testArr);
const hex = booleanArrayToHex(testArr);
console.log('test hex', hex);
const resultArr = hexToBooleanArray(hex, rndLength);
console.log('test resul', resultArr);
const same = testArr.reduce((acc, it, index) => {
return (acc && resultArr[index] === it);
}, true);
console.log('is same', same);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment