Wednesday, August 26, 2009

Decimal or Integer to Binary / AS3 Code

I had a need for this routine in Protonaut, and Ryan Madsen was gracious enough to pseudo-code this up for me. I then converted it to proper AS3 and to suit protonaut's needs.

It's modifiable easily enough, but here's the basic premise:

Input a decimal (say, the number 1) and request an array length in return (default 6 bits).

It will convert the decimal to binary, and store each bit into an array in reverse order for easy flag operation. Our example of 1 would then return [1,0,0,0,0,0].
  private function dec2bin(dec:uint, digits:Number=6):Array {
var result:Array = new Array();
for (var i:Number = 0; i <= digits-1; i++) result[i] = 0; for (var i:Number=digits-1; i >= 0; i--) {
if ((dec - Math.pow(2,i)) >= 0) {
result[i] = 1;
dec -= Math.pow(2,i);
return result; // results are in reverse order... 1 == 1,0,0,0,0,0

I used this code for retrieving a single ascii charcode to store the combinations of the various 6 keys you can press in the game. I googled around and couldn't find anything, so hopefully this will help someone else.

This is easily converted to outputing the Binary to String format, or reversing the Array, if you so need.

No comments:

Post a Comment