Created
December 1, 2012 10:16
-
-
Save CatTail/4181403 to your computer and use it in GitHub Desktop.
Javascript: convert negative number into binary
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
// Handler negtive number into binary. | |
// The code following is really meanless for number itself is depend on it's | |
// length. For instance, in bit operation, number will be treated as 32 bit. | |
// @see http://stackoverflow.com/questions/4338315/javascript-inverting-a-binary-value-of-a-number | |
function dec2Bin(dec) | |
{ | |
if(dec > 0) { | |
return dec.toString(2); | |
} | |
else { | |
//make the number positive | |
dec = Math.abs(dec); | |
//get the first compliment | |
var res = dec ^ parseInt((new Array(dec.toString(2).length+1)).join("1"),2); | |
//get the second complimet | |
return (res+1).toString(2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment