Skip to content

Instantly share code, notes, and snippets.

@Mellen
Last active May 29, 2019 19:24
Show Gist options
  • Save Mellen/7551988 to your computer and use it in GitHub Desktop.
Save Mellen/7551988 to your computer and use it in GitHub Desktop.
This turns any positive integer into its binary representation, but as an integer, so it's not really binary. Just a fun thing I figured out.
var p = Math.log(20)/Math.log(2) - 1;
function binarise(x)
{
if(x === 0)
{
return 0;
}
if(x === 1)
{
return 1;
}
if(x < 0)
{
throw 'not implemented for negative numbers';
}
if(x > 0 && x < 1)
{
throw 'not implemented for non-integers';
}
if ((x & (x - 1)) != 0)
{
var bit = prevIntPoT(x);
var leftover = x - bit;
return binarise(bit) + binarise(leftover);
}
var result = Math.floor(Math.pow(x, p));
if(result == Number.POSITIVE_INFINITY)
{
throw 'The input is too big.'
}
return result;
}
function prevIntPoT(x)
{
return 2**(x.toString(2).length - 1);
}
@Mellen
Copy link
Author

Mellen commented Nov 20, 2013

rounding errors mean that problems occur after 32767

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment