Skip to content

Instantly share code, notes, and snippets.

@Sharlottes
Last active February 1, 2024 03:14
Show Gist options
  • Save Sharlottes/aa2f2f2051e7b071264357117a00dc29 to your computer and use it in GitHub Desktop.
Save Sharlottes/aa2f2f2051e7b071264357117a00dc29 to your computer and use it in GitHub Desktop.
// @ts-check
const BITS = 8;
function encode(...nums: number[] ) {
let num = 0;
for (let i = 0; i < nums.length; i++) {
num |= nums[i] << (i * BITS);
}
return num;
}
function decode(num: number, amount: number) {
const arr = [];
const mask = 2 ** BITS - 1;
for (let i = 0; i < amount; i++) {
arr.push(num & mask);
num >>= BITS;
}
return arr;
}
console.log(encode(2))
console.log(decode(encode(1),1))
const BITS = 8;
function decode(num: number, amount: number) {
const arr = [];
const mask = 2 ** BITS - 1;
for (let i = 0; i < amount; i++) {
arr.push(num & mask);
num >>= BITS;
}
return arr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment