Skip to content

Instantly share code, notes, and snippets.

@CatTail
Created December 1, 2012 10:16
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 CatTail/4181403 to your computer and use it in GitHub Desktop.
Save CatTail/4181403 to your computer and use it in GitHub Desktop.
Javascript: convert negative number into binary
// 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