Jump to content

JavaScript example: Converting a decimal to binary


Semperfidelis

Recommended Posts

There is an example under JavaScript bitwise title which says here is how to convert a decimal to binary:

document.getElementById("demo").innerHTML = dec2bin(-5);
function dec2bin(dec){
  return (dec >>> 0).toString(2);
}

I do not quite follow what is happening inside the function, and when does -5 convert to binary. What happens to -5 as a decimal once it is passed to the function? I mean, I can just try to remember it, but given the context of the topic and the operators discussed earlier in this section, I do not see what is happening. I also found a thread on SO about it here. But it did not help, it just says how to do it. If the example is just meant to show how to convert binary to decimal, that is fine. I just want to make sure I am not missing anything.

Edited by Semperfidelis
Link to comment
Share on other sites

The ">>> 0"  part converts the signed integer into an unsigned one, so that you can get the computer's actual representation of negative numbers. The ".toString()" part is the one that does the conversion to binary. When you put "2" as an argument it indicates that you want a base 2 representation, which is binary. If you gave it "10", it would give you the number in our familiar decimal system.

For negative numbers, what you'll get is the way computers represent negative binary numbers. A negative binary number is represented by subtracting 1 from its positive value and then flipping all the bits, which means switching 0s for 1s and 1s for 0s. The reason they subtract 1 is because if they did not, there would be such thing as negative zero, which doesn't make sense in regular math.

Keep in mind that this is only how computers represent negative numbers. In real binary a negative number is just a positive one with a "-" preceding it just as in the decimal system. If you want the mathematical binary representation then remove the ">>> 0" part.

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...