Previous Tip  |  Next Tip  |  Design Tips   | [Bill's Home]

# Flash and Binary Numbers

[Expand] The great thing about Flash is that with the power of Actionscript it produces excellent integrated applications, with the minimum of fuss. For a while I've wanted to add an example of Flash using binary numbers and for this I've produce the following:

You should find that the binary numbers produced are random, and I achieved this with the script:

 dec1= "w"; dec2="x"; dec3="y"; dec4="z"; val1=random(224); bin1=tobinary(val1); val2=random(254); bin2=tobinary(val2); val3=random(254); bin3=tobinary(val3); val4=random(254); bin4=tobinary(val4); function tobinary(val) { var i:int; str=""; for (bit=0;bit<8;bit++) { j=int(val%2); if (j==0) str=str+"0"; else str=str+"1"; val=int(val/2); trace(val); } tmp=str; str=""; for (i=7;i>=0;i--) { str=str+tmp.slice(i,i+1); } return(str); }

You can see that the four decimal numbers are intially created with:

val1=random(224);
bin1=tobinary(val1);

val2=random(254);
bin2=tobinary(val2);

val3=random(254);
bin3=tobinary(val3);

val4=random(254);
bin4=tobinary(val4);

then the bin1, bin2, bin3 and bin4 strings are generated using the function:

function tobinary(val)
{
var i:int;
str="";
for (bit=0;bit<8;bit++)
{
j=int(val%2);
if (j==0) str=str+"0";
else str=str+"1";
val=int(val/2);
trace(val);
}

tmp=str;
str="";
for (i=7;i>=0;i--)
{
trace(tmp.slice(i,i+1));
str=str+tmp.slice(i,i+1);
}

return(str);

}

The first part (in blue) converts to the value to a string with binary values ('1' or '0'). Unfortunately this conversion is now the wrong way round, as the least significant bit is produced first, and the most sigificant bit, last. Thus the next part of the function (in red) reverses the order.

For the button the following actionscript can be added to determine if the user has selected the correct answers:

on (press) {
corr=0;
incorr=0;
if (dec1==val1) corr++;
else incorr++;

if (dec2==val2) corr++;
else incorr++;

if (dec3==val3) corr++;
else incorr++;

if (dec4==val4) corr++;
else incorr++;

if ((va1<128) && (ipclass.currentvalue=="Class A")) corr++;
else if ((val1>=128) && (val1<192) && (ipclass.currentvalue=="Class B")) corr++;
else if ((val1>=192) && (val1<224) && (ipclass.currentvalue=="Class C")) corr++;
else incorr++;

correct=corr;
incorrect=incorr;

if (corr>4)gotoAndPlay (10);

}

In summary, throw your Visual Basic, your Director and your Java. For simple, graphical programs, which can be viewed over the WWW, there's only one choice: Macromedia Flash. Apart from Microsoft Word and Microsoft Excel, the most powerful and useful program ever created.