Skip to content

Instantly share code, notes, and snippets.

@ChiriVulpes
Last active May 9, 2021 20:57
Show Gist options
  • Save ChiriVulpes/34096240ef23ba918a4de62293c387e9 to your computer and use it in GitHub Desktop.
Save ChiriVulpes/34096240ef23ba918a4de62293c387e9 to your computer and use it in GitHub Desktop.
vec2i serialize/deserialize to single int
export type Vec2i = readonly [x: number, y: number];
export namespace Vec2i {
export function serialize (...[x, y]: Vec2i) {
let number = 0;
let i = 0;
while (x || y) {
let val;
if (i % 2) {
val = y;
y >>= 1;
} else {
val = x;
x >>= 1;
}
number |= (val & 1) << i++;
}
return number;
}
export function deserialize (n: number): Vec2i {
let x = 0;
let y = 0;
let i = 0;
while (n) {
const val = n & 1;
n >>= 1;
if (i % 2) {
y |= val << (i >> 1);
} else {
x |= val << (i >> 1);
}
i++;
}
return [ x, y ];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment