Jump to content
Semperfidelis

JavaScript example: Converting a decimal to binary

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

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

Thank you so much. This was exactly what I was missing. I had to refresh my memory on binary representation, but I am good now. Just in case someone else may want to know the details this link was very helpful for me.

Edited by Semperfidelis

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...