Recipe 4.1.
Representing Numbers in Different Bases
Problem
You
want to specify a value in
binary, octal, or hexadecimal.
Solution
Hexadecimal literals start with 0x
(where the first character is a zero, not an "oh"), and octal literals start with 0
(again, zero, not "oh"). Binary numbers can't be represented
directly, but you can either specify their octal or hexadecimal
equivalent or use the parseInt( ) function to convert a
string to a number.
Discussion
You can represent numbers in ActionScript using
whichever format is most convenient, such as decimal or hexadecimal
notation. For example, if you set the value of the Sprite.rotation property,
it is most convenient to use a decimal number:
rectangleSprite.rotation = 180;
On the other hand, hexadecimal numbers are
useful for specifying RGB colors. For example, you can set the
rgb value for a ColorTransform object in
hexadecimal notation (in this example, 0xF612AB is a hex
number representing a shade of pink):
var pink:ColorTransform = new ColorTransform( );
pink.rgb = 0xF612AB;
Any numeric literal starting with 0X or
0x (where the first character is a zero, not an "oh") is
presumed to be a hexadecimal number (i.e., hex or
base-16). Allowable digits in a hexadecimal number are 0 through 9
and A through F (upper- and lowercase letters are equivalent,
meaning 0xFF is the same as 0xff).
Any numeric literal starting with 0
(again, zero not "oh"), but not 0x or 0X, is
presumed to be an octal number (i.e., base-8). Allowable
digits in an octal number are 0 through 7; for example,
0777 is an octal number. Most developers don't ever use
octal numbers in ActionScript. For most developers it's simply far
more convenient to represent most numbers as decimal numbers
(base-10), except color values for which it is generally more
convenient to use hexadecimal representation. There aren't many
common examples for which octal representation is more convenient
than decimal or hexadecimal.
The only digits allowed in binary numbers
(i.e., base-2) are 0 and 1. Although you can't specify a binary
number directly, you can specify its hexadecimal equivalent. Four
binary digits (bits) are equivalent to a single hex digit.
For example, 1111 in binary is equivalent to F in
hex (15 in decimal). The number 11111111 in binary is
equivalent to FF in hex (255 in decimal). Binary numbers
(or rather their hexadecimal equivalents) are most commonly used
with ActionScript's bitwise
operators (&,
|, ^, >>, <<, and >>>).
See Also
Recipe
4.2
|