Last active
May 19, 2023 18:43
-
-
Save m93a/2a728e30356f7e7e76925de3b66a2290 to your computer and use it in GitHub Desktop.
Save data into a NaN (only works in V8)
This file contains 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
const MSB = 1 << 7; | |
const nanbox = (message: string): number => { | |
const float = new Float32Array(1); | |
const bytes = new Uint8Array(float.buffer); | |
bytes[3] = ~MSB + (MSB & message.charCodeAt(0)); | |
bytes[2] = MSB + (~MSB & message.charCodeAt(0)); | |
bytes[1] = message.charCodeAt(1); | |
bytes[0] = message.charCodeAt(2); | |
return float[0]; | |
}; | |
const nunbox = (nan: number): string => { | |
const float = Float32Array.from([nan]); | |
const bytes = new Uint8Array(float.buffer); | |
return ( | |
String.fromCharCode(bytes[3] & (MSB + bytes[2]) & ~MSB) + | |
String.fromCharCode(bytes[1]) + | |
String.fromCharCode(bytes[0]) | |
); | |
}; | |
const message = "Sup"; | |
const boxed = nanbox(message); | |
console.log(boxed); // NaN | |
const unboxed = nunbox(boxed); | |
console.log(unboxed); // Sup |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment