Last active
May 9, 2021 20:57
-
-
Save ChiriVulpes/34096240ef23ba918a4de62293c387e9 to your computer and use it in GitHub Desktop.
vec2i serialize/deserialize to single int
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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