Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

6
  • 1
    doesn't work for -1. a=-1; document.write(Number(a.toString(2))); displays -1 Commented Mar 30, 2012 at 9:05
  • The update still doesn't appear to work for negative numbers (-3 returns 1). Also I believe dec > 0 should be dec >= 0, which should at least fix 0. Because dec2Bin(0) returns 10. Commented Apr 15, 2014 at 21:17
  • Both cases in above comments return correct result in my chrome console - var a = -1; a.toString(2); "-1" var a = -3; a.toString(2); "-11" Commented Jul 9, 2014 at 12:01
  • @AnmolSaraf I see what you mean, and while colloquially when people say what is -5 in decimal, and the answer is -5 When it comes to negative numbers in binary , in a sense yeah you could stick a minus sign there so 5 is 101 and -5 is -101 but since computers don't store minus signs, they just represent 1s and 0s, so when we say negative numbers in binary, we really mean putting the negative number (minus sign included) in 1s and 0s. Some ways include 1s complement, 2s complement, and 'sign and magnitude'. So -101010101 or -0101010 is not what people mean by a negative number in binary. Commented Apr 10, 2015 at 10:59
  • This link may be of interest to some stackoverflow.com/questions/12337360/… anyhow, Your answer contradicts itself, you write "Javascript represents negative binary integers in two's-complement notation." And your code says " Here you could represent the number in 2s compliment but this is not what JS as uses as [nonsense reason] " And you give no reference either. Commented Feb 22, 2016 at 12:05