AS3 Decimal to Binary, Octal and Hexadecimal Convverter

/, Blog/AS3 Decimal to Binary, Octal and Hexadecimal Convverter

This converts decimal into binary, octal and hexadecimal. I have no idea why I made this. In fact, there’s probably a native function that does this ten times quicker. It was fun, though. Call it an adventure into user input.


[kml_flashembed publishmethod=”static” fversion=”9.0.0″ movie=”http://johnbarrett.net/wp-content/uploads/2013/01/BinaryConverter.swf” width=”400″ height=”300″ targetclass=”flashmovie”]

Get Adobe Flash player

[/kml_flashembed]
The real work is in converting decimal to binary. To do this, you have to repeatedly divide by two (the base). In doing this, you’ll get either a “1” or a “0” as a remainder. You can use the modulus operator  to do this, but I just divided by two and later checked to see if the floor of the number was equal to the original number. If so, then there was no remainder, and I added a “0”. Otherwise I added a “1”.

Going from binary to octal and hex is very easy. You just need to split the binary string into lengths of three and map this new value into binary. For instance, the string “101111001” can be split into three units: 101, 111, and 001. These, in turn map to the binary values of “5”, “7”, and “1”. So, 101111001 base 2 (binary) equals 571 base 8 (octal).

Binary to hex is just as easy, only you have to split the string into units with lengths of 4. So, 11110010 is split into “1111” and “0010”, which in hex is “F2”.

One problem that I ran into during this project was the use of the TextField’s TEXT_INPUT TextEvent. It sucks, and unless I’m missing something I see no real reason to use it. It lags by one character, so that if you type in “hello world”, your app thinks that “hello worl” has been entered. It shortens the incoming string by one character. I found that getting the TextField’s data with a  “KEY_UP” Keyboard event is more accurate. The only drawback is that you either have to constantly listen for the KEY_UP event, or you do as I did here: start listening when the TextField’s FOCUS_IN event fires and stop listening on FOCUS_OUT (this uses AS3’s  FocusEvent. There are probably other solutions, but this worked great for me.

By | 2013-01-06T18:59:03+00:00 January 6th, 2013|Actionscript 3.0, Blog|0 Comments

About the Author:

Leave A Comment