Skip to content

Instantly share code, notes, and snippets.

@arnorhs
Forked from 140bytes/LICENSE.txt
Last active December 15, 2015 13:39
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 arnorhs/5268995 to your computer and use it in GitHub Desktop.
Save arnorhs/5268995 to your computer and use it in GitHub Desktop.
function(
o, // either the object hash passed in to pack it, or the integer passed in which will be returned as an object hash
p // placeholder
) {
p=1<<26; // Shorter than Math.pow(2,26)
return o.a ? // checking if it's an object
o.a*p+o.b : // it is, so we pack by taking the .a property, multiply it with p, and add b to it
{
a:o/p|0, // it is not, so we divide by p, and |0 will floor the variable
b:o%p // the reminder should be the second variable
};
}
function(o,p){p=1<<26;return o.a?o.a*p+o.b:{a:o/p|0,b:o%p};}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 YOUR_NAME_HERE <YOUR_URL_HERE>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "packOrUnpackTwo26bitIntegers",
"description": "Javascript only does bitwise oprerations on 32 bits. This code bypasses that by doing multiplication and division.",
"keywords": [
"pack",
"packing",
"integer"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>undefined</b></div>
<div>Before packing: <b id="before"></b></div>
<div>Packed: <b id="packed"></b></div>
<div>Unpacked: <b id="unpacked"></b></div>
<script>
// we want to pack these two integers which are too big for doing bitwise operations (js only does bitwise operations on 32 bits)
var packer = function(o,p){p=1<<26;return o.a?o.a*p+o.b:{a:o/p|0,b:o%p};}
var before = {a: 1337, b: 100000};
var packed = packer(before);
var unpacked = packer(packed);
document.getElementById("before").innerHTML = before.a + " and " + before.b;
document.getElementById("packed").innerHTML = packed;
document.getElementById("unpacked").innerHTML = unpacked.a + " and " + unpacked.b;
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment