Pushing the boundaries

…couldn’t be any simpler!

integer overflow

Posted by vijayram on February 4, 2007

Santosh Kumar over on the iGeeks brought to my attention about this interesting topic. I never have dug in deep to learn about this subject, since I know it could cause more harm đŸ˜‰

He mentioned: ” While type casting from Number (64-bit double-precision) to int (32-bit integer) if Number value range cannot fit into integer than integer value is converted to default value ie 0.”

Interesting, but why should it default to zero?! That begged the question. Let me retrospect from my earlier post. I mentioned, anything over the range of Integer values, shall be internally operated as a “Number” data-type in Flash.

var i:int = 2147483648;
<type name=”Number” base=”Object” isDynamic=”false” isFinal=”true” isStatic=”false”>
<extendsClass type=”Object”/>
<parameter index=”1″ type=”*” optional=”true”/>

Wait a minute, we just came across an example of “integer overflow“! When an attempt is made to store a value greater than this maximum value it is known as an integer overflow. Why didn’t the compiler warn me? Apparently where is no compile-time warnings or run-time exceptions to let you this.
Integer overflows cannot be detected after they have happened, so there is not way for an application to tell if a result it has calculated previously is in fact correct. This can get dangerous if the calculation has to do with the size of a buffer or how far into an array to index.

Ok, time to understand what is happening here. Lets take the case of both the unsigned integer and signed integer overflows (there are overflows and underflows).
When an unsigned integer reaches its maximum value, it wraps around and starts over, much as a car odometer. Unsigned short integers can’t hold a number larger than 4294967295, so the value is wrapped around to 0.

var i:uint = 4294967296; //overflow
// output – 0

A signed integer is different from an unsigned integer, in that half of the values you can represent are negative. Instead of picturing a traditional car odometer, you might picture one that rotates up for positive numbers and down for negative numbers. One mile from 0 is either 1 or -1. When you run out of positive numbers, you run right into the largest negative numbers and then count back down to 0.

var i:int = 2147483648; // overflow
//output – -2147483648 (this is largest negative int value)

Why is this important to know??Supposing you are working with unsigned data-type, the memory would be allocated for it accordingly. If that value has wrapped around then there would be far little memory for it now available. Disaster. Or if you are comparing values with a signed integer and it has overflown to be a negative, it would it pass througn. Disaster again!! If an attempt is made to store a value in an integer which is greater than the maximum value the integer can hold, the value will be truncated. If the stored value is the result of an arithmetic operation, any part of the program which later uses the result will run incorrectly as the result of the arithmetic being incorrect.

Now, think of what impact this could have. One could exploit this if it has not been taken care for in the Flash Plugin. One cannot directly overwrite the memory but the exploitation can be subtle. This topic is out of the subject for this current post but you can read about it here on Wikipedia. Flash plugin was prone to heap buffer read overflow in the recent past.
Microsoft have there version of SafeInt class to help safeguard from this issue. All arithmetic is performed on unsigned values, which is very interesting.

Now back to Flash. Any number too big is just returned back as “infinity”. Clever!!! But why?
Lets just remember that Flash uses another data-type for arithmetic operations called “Number”. The Number data-type interoperates as “double” data-type which means it has a larger range of numbers it can store and display.

Through some debugging process, I came to know that Flash uses “int” data-type to represent any values between the range 2^29 (-268435456 to +268435455). I am not sure what happens to those extra 3 bits, though one bit would be used for the sign (+ or-). Anything over this range is held internally as a Number data-type to represent. What this implies is that, we do not have our flash player crashing if we have an overflow or underflow as this implicit casting happens internally. Anything over the range of Number will be called as “infinity”.


Posted in Adobe, AS 3.0, Flash, Programming | 3 Comments »

int vs Number

Posted by vijayram on February 1, 2007

This issue was highlighted by Sho Kuwamoto sometime back who recommends to use Number where ever possible. Grant Skinner made some additional test and has posted his results here.

While looking through the code on tamarin on the class construct for Number, it is defined as a 64-bit double-precision floating-point number while, int and uint are 32-bit each. So technically both int and uint use 4bytes in the memory whilst Number uses 8 bytes of memory.

From, the Flex doc it says: “When you store integer values with the Number data type, only the 52 bits of the significand are used. The Number data type uses these 52 bits and a special hidden bit to represent integers from -9,007,199,254,740,992 (-253) to 9,007,199,254,740,992 (253)”. Explains the 64-bit range.

By looking through tamarin, it is evident what the maximum and minimum value you can store for each of these data types.
For Number:
public static const MIN_VALUE :Number = 4.9e-324
public static const MAX_VALUE :Number = 1.7976931348623158e+308
For int:
public static const MIN_VALUE:int = -0x80000000;
public static const MAX_VALUE:int = 0x7fffffff;
For uint:
public static const MIN_VALUE:uint = 0;
public static const MAX_VALUE:uint = 0xffffffff;

I was actually digging through the notes on tamarin just to see how things work and why we have this variations in speed.
It so happens that, almost all the numbers ranges that we use to code falls between the max and min values of an integer (-2,147,483,648 to 2,147,483,647). Flash does an implicit conversion at runtime for any values we pass between this range to an integer. Even if you pass a floating point to a variable data-typed as int.How did I know this?

The flash.utils package contains a method called describeType. Equipped with this function, call this on your variable which contains the value and you shall the result as follows:
<type name=”int” base=”Object” isDynamic=”false” isFinal=”true” isStatic=”false”>
<extendsClass type=”Object”/>
<parameter index=”1″ type=”*” optional=”true”/>

Even if your variable is data-typed to be a Number it still is converted to “int”. Now what happens if we exceeds the rage for Integer? It is automatically converted into a Number as it has a larger range than integer. Clever! What about uint? It is again converted to int.

Now go back to Grant Skinner’s test results and you shall see why int outperforms in most cases. As you are aware, Number data-type can accepts decimal values and hence floating-point operator(multiplication and division) is quicker when data-typed to Number.
So to avoid this performance overhead of implicit conversion, its better to data-type your variable to “int” during addition and subraction and whilst division and multiplication is involved use “Number” data-type.

Technorati Tags: , , ,

Posted in Adobe, AS 3.0, Flash, Programming | Leave a Comment »

native function

Posted by vijayram on January 31, 2007

Ok, this is a cool modifier. While I was looking through the notes on ActionScript 3.0, I did notice a reserved keyword called “native”. I had worked with native implementation in JAVA(JNI), so this really got me excited.Why?!

The reason being, the use of native functions indicates that the method is implemented externally. In a DLL maybe? ;). So, there maybe possiblities to call native windowsAPI from the swf…hmmm. Using this abstract modifier means that the method implementation is not provided in the class.Because an external method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no braces ({ }) following the signature.

native function functionName();
class className {
native function methodName();

So I started rummaging through the Flash Player code, and voila they use native functions as a part of implementation. What this means is that the native functions available to the Virtual Machine is called for through this function call using ActionScript.

//pseudo-final – no user class can extend Class
public dynamic class Class
// {DontEnum,DontDelete,ReadOnly}
public native final function get prototype()

// Class.length = 1 per ES3
// E262 {ReadOnly, DontDelete, DontEnum }
public static const length:int = 1;

The above is the actual code for a top level Class construct in the Virtual Machine which is available on tamarin.
Ok, the next obvious step, can I call for it from my code and override it if possible?!

Sadly not!!!! It turns out that Flash Player uses this internally and I cannot use it in my code as explained here.

Posted in Adobe, AS 3.0, Flash, Programming | Leave a Comment »

Garbage Collector

Posted by vijayram on January 31, 2007

Adding to the post on Stacks and Heaps, I had to link to this blog about the internal workings of Garbage Collector in ActionScript 3.0.

Grant Skinner on Resource Management . If that’s not enough, he has published his talks on Garbage Collector using visual simulators here.

*Some side notes:
– You cannot delete class members in ActionScript 3, if you want to cause a variable to no longer reference an object or value in memory, you should set your variable’s value to null instead of deleting it. [ myVar = null; ]
If all variable references to an object are null, the Garbage Collector will mark it for deletion and it will eventually be cleared from memory.
There is a post hereby Gordon Smith explaning the same.
– Ted Patrick has an interesting post on “flash.system.System.totalMemory” saying it just represents the memory allocated to the FlashPlayer. So it might not be the best util to check for memory leaks when you remove objects by setting it to null. You can learn about System.totalMemory here.
– FlashLite has this profiling for sometime now showing the heap memory usage. Pretty cool using the emulator tool. Any questions on that can be directed to IndiMad which is managed by Mariam.

Technorati Tags: , , ,

Posted in Adobe, AS 3.0, Flash, Programming | Leave a Comment »

Stacks and Heaps

Posted by vijayram on January 30, 2007

Someone asked me this question and I wasn’t in the best position to reply back then. This time I will take the effort of writing it down for future reference and for the benefit of all.

Simple explanation would be, stack is allocated before the program executes, where the heap contains memory allocated during the program run.

Using ActionScript for Flash, you can keep track of how much memory Flash Player uses at run-time using the System.totalMemory method.

To begin with data can be of two types, Value or Reference. Although there are many data types, they are always treated: as primitive (also called Value) and by Reference. It is important to note where this data is stored. Value types are stored in “stack” and Reference types are stored in the “heap”. Lets look at this way, objects created on the fly(ie: using the “new” keyword) is stored in the heap while variables will be stored in the stack.

Both Stack and Heap work together. Stack works on basis of last-in, first-out (LIFO). This would be the top-most in the pile would be removed first. Once an object has been instantiated from a class, it is moved into the heap.

During the course of the program running, the heap is polluted with unused data reference which doesn’t exist anymore. This is when the Garbage Collector kicks in. It is the role of the Garbage Collector to clear the heap of unused references or data, else you will have a memory leak, causing the program to come to a grinding halt!

Garbage Collector which is part of the ActionScript Virtual Machine uses several techniques to clear up the data of the heap. There is a “reference counting” technique and there is also a “mark and sweep” technique. From my understanding Garbage Collector in Flash Player 9 uses a deferred method whereby, based on certain factors, the Garbage Collector will kick-in and not by merrily removing the reference to the object in code clears up the heap.

Technorati Tags: , , ,

Posted in Adobe, AS 3.0, Flash, Programming | Leave a Comment »

ActionScript code tricks

Posted by vijayram on January 30, 2007

Continuing with the post, today’s tricks are to do with bitwise operators for manipulation of colours.

After working on the visualizer, it became obvious to me that one needs to know the nitty grittys of assisgning colours and manipulating the same using ActionScript. Working through this reminded me of the days I implemented RSA encryption in FLash 5. Bits, Bytes, hex…..hmm…geek time!

Starting with basics of number theory, we in our day to day life deal with numbers using a base 10. For example, Shilpa Shetty in Celebrity Brother was paid £300,000 for apperance.
300,000 = (3 x 100000)+(0 x 10000)+(0 x 1000)+(0 x 100)+(0 x 10)+(0 x 1)
300,000 = (3 x 10^5)+(0 x 10^4)+(0 x 10^3)+(0 x 10^2)+(0 x 10^1)+(0 x 10^0)

Whilst in computers, everything is represented using base 2 system (ie: 0 and 1).
100010 = (1 x 2^5) + (0 x 2^4) + (0 x 2^3) + (0 x 2^2) + (1 x 2^1) + (0 x 2^0) = 34

Moving on, colours are represented as hexadecimal. This basically means that, it is to the base 16. Simple!. They are represented as: numbers 0 to 9 and the letters A to F. For example, the decimal number 12 is C in hexadecimal.

Colour values in ActionScript is represented using a 32 bit hexadecimal or 4 pairs of hexadecimal digits( one hexadecimal digit = 4 binary digit). I said 4 pairs here, which means each channel makes a hexadecimal pair (Alpha, Red, Green and Blue). Opaque images are 24-bit, with 8 bits for each of its red, green, and blue channels. Transparent images add another 8-bit alpha channel for a total of 32 bits.

So far a 32-bit image, it is AARRGGBB.

Moving on, lets take case of bitwise OR (“|”). Do not confuse this with logical OR. This sets the result bit to 1 if either of the source bits is 1.
0101 OR 0011
= 0111
Several ActionScript gurus use this operator while playing with colours [ eg:graphics.lineStyle(num,0x0033FF|(num << 8)); ]
Lets just put it this way, its a celver way for combining colours. You can use the bitwise OR to combine BitmapDataChannel constants to indicate multiple color channels.
bitmap.perlinNoise(100, 100, 5, 500, false, true, BitmapDataChannel.RED | BitmapDataChannel.GREEN | BitmapDataChannel.BLUE,false, null);

The next operator is shift, Left Shift “<<” and Right Shift “>>”. The left operands value is moved left or right by the number of bits specified by the right operand.
In theory, 00001110 << 2 = 00111000.
Actionscript converts the result to a 32-bit integer, which is good in our case for colours.
Shift operators discard anything after the decimal place, so shifting by zero provides a faster way to floor your numbers:
trace(1234.567>>0); // 1234
Now coming back to our bitmap representation, AARRGGBB we know that it is represented as follows: aaaaaaaarrrrrrrrggggggggbbbbbbbb (8 bits for each channel).

Given an RGB colour, if we want to extract only red, we do as follows:
myRed = myRGB >>16; This would move the bits to the right by 16 place, thereby discarding all the G and B bits and we are left with only R :). But its still padded with those trailing zeros.

The next and the last operator we are going to look at is &. Again this is different from logical and”&&”.
The & operator performs a bitwise AND on two integers. Each bit in the result is 1 only if both corresponding bits in the two input operands are 1. For example:
0 1 0 1 0 1 1 0
& 0 0 1 1 0 0 1 0
0 0 0 1 0 0 1 0
This is a clever operator and used for masking. Masking is nothing but to mask the other bits and extract the ones you want. Interesting!
Lets take the earlier example of extracting the red channel, its easier to do with this operator as follows:
var argb:Number = 0xFFAA341B;
var redChannel:Number = (argb & 0x00FF0000) >> 16;
trace(“redChannel: “+redChannel.toString(16)); //output redChannel: AA

Technorati Tags: , ,

Posted in Adobe, AS 3.0, AS code tricks, Flash | Leave a Comment »


Posted by vijayram on January 29, 2007


package {

import flash.display.Sprite;
import flash.media.Sound;
import flash.utils.ByteArray;
import flash.media.SoundMixer;
import flash.events.Event;
import flash.net.URLRequest;

[SWF( backgroundColor=”0x000000″, frameRate=”31″, width=”200″, height=”200″)]
public class wpSpectrum extends Sprite {

private var _bytes:ByteArray;

public function wpSpectrum() {
var s:Sound = new Sound(new URLRequest(“mySong.mp3”));
_bytes = new ByteArray();
addEventListener( Event.ENTER_FRAME, onEnterFrame );

private function onEnterFrame( event: Event ): void {

SoundMixer.computeSpectrum(_bytes, true, 0);
var value:Number;


var spacing:Number = (stage.stageWidth / 256);
var color:Number;

for(var i:int = 0; i < 256; i+=16) {
value = _bytes.readFloat();
value = (value * 256) << 0;
color = 0x00FF00|(value << 16);
graphics.lineStyle(1, color, 1);


Posted in Adobe, AS 3.0, Flash | 1 Comment »

Visualizer in Actionscript 3.0

Posted by vijayram on January 26, 2007

Compute Spectrum

Spectrum analyzer using SoundMixer.computeSpectrum

Posted in Adobe, AS 3.0, Flash | 4 Comments »

Pure ActionScript 3.0 AudioPlayer

Posted by vijayram on January 26, 2007


Quite a while back I started playing with Flashdevelop which was introduced to me by one of my work mates. I couldn’t let time go by until Flash9 IDE is eventually released. There are a lot of info out in the www space on how to get it working for Flex 2 and AS 3.0 projects. I am amazed by its simplicity. Kudos to the team behind it.

Back to the post. Since not many projects and resource are out there for AS 3.0 projects, it took me sometime to figure out on how things work. What I was after was pure ActionScript 3.0 code and hence I made this rough AudioPlayer using the power of AS 3.0. One source of inspiration were the experiments done by “andrĂ© michelle“.

If anybody does need the source or need to know how things work, drop a note. This might not be the best implementation but certainly gives a head start. I can think of ways to make things look better….

Posted in Adobe, AS 3.0, Flash | 1 Comment »

ActionScript code tricks

Posted by vijayram on January 26, 2007

Continuing this topic, today I shall discuss the benefits of CONSTANTS. I have seen several programmers use it in AS 2.0, but with AS 3.0 to me, it all made sense.

CONSTANTS are all uppercase and spaces converted to underscore. (eg: SERVER_NAME=”god”;)
Values assigned to CONSTANTS do not change as it implies. Declaring a CONSTANT is rather straight forward as declaring a variable with the var keyword.
public static const SERVER_NAME:String =”god”;

In ActionScript 3.0, the one place you will always encounter CONSTANTS are Events. It is best code of practice to use static CONSTANTS property of the Event class.(eg: addEventListener(Event.ENTER_FRAME, onEnterFrame); )

Lets just understand why we require to use the static CONSTANTS, as supposed to using just “enterFrame”. ActionScript 3.0 is a dynamically typed language and also supports compile-time type checking using the “strict mode”. I could type the above Event as follows, which is still valid – addEventListener(“enterFrame”, onEnterFrame);
But what if I were to type it as follows – addEventListener(“enterFame”, onEnterFrame);

I would definitely have “entered Fame” but for all the wrong reasons. The above code would be still compiled by the compiler though no errors will be reported. I would be spending unnecessary time to debug this. To avoid any such mistakes it is better to use the CONSTANT property of the class. How to we create one for our class?

This brings us to another topic of Enumerations. Enumerations are custom data types that you create to encapsulate a small set of value. ActionScript 3.0 does not support a specific enumeration facility like C++ or Java, however you can create this behaviour using classes and static CONSTANTS.

For example, a visitor to a web-page has a choice of language. The LanguagePreference class will use an enumeration PrefLanguage to store a set of language values.
public final class PrefLanguage {
public static const ENGLISH:String = “english”;
public static const FRENCH:String = “french”;

Now you can access the enumeration values as follows:
var myLanguage:LanguagePreference = new LanguagePreference();
if ( myLanguage.Language ==PrefLanguage.ENGLISH){

The advantage of using the above method is that your code is type-safe, thereby catching errors at compile time. The only disadvantage that I can think of is the need for an additional class to be written to hold your enumeration types.

Posted in Adobe, AS 3.0, AS code tricks, Flash | 4 Comments »