Skip to content

Instantly share code, notes, and snippets.

@m93a
Last active May 19, 2023 18:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m93a/2a728e30356f7e7e76925de3b66a2290 to your computer and use it in GitHub Desktop.
Save m93a/2a728e30356f7e7e76925de3b66a2290 to your computer and use it in GitHub Desktop.
Save data into a NaN (only works in V8)
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