Last active
May 29, 2019 19:24
-
-
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.
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
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
rounding errors mean that problems occur after 32767