How to convert decimal to unsigned binary in JavaScript

Ok, I do have to admit that this has limited value. I did this mostly as a thought experiment. I wanted to see how easy it would be to script the conversion from decimal to binary and back again, in JavaScript.

 

[gist id=7404064 file=DecimalToBinary.htm bump=3]

 

As you can see, the conversion from binary to decimal is much easier than decimal to binary. Before you ask, I do know that toString() can convert decimal to binary, octal, and hexadecimal but that would not have been as fun. 🙂

Live Demo

Edit: I updated BinaryToDecimal(). There was a significant flaw in it. After talking the problem over with Jeremy Streich, I also decided that this could be refactored to be much more simple. I’ll probably wait on writing a revision, though. I want to try hex and octal sometime soon and I’ll revisit this as part of that.

Leave a Reply

Your email address will not be published. Required fields are marked *