So, I was re-visiting some code the other day and thinking about how it could be optimized. I really wanted to focus on calculation speed/runtime execution and I remembered glancing at bitwise operators in the ActionScript Documentation back in the day but never really dug into what lies beneath…
As defined: A bitwise operation is one that affects 1 or 2 binary numbers on a bit level.
Background Binary Understanding:
Bits are like little containers for storing information and they can only contain one of two states.
Examples:
(3 bits) : 101
(8 bits or 1 byte) : 10110110We know that a binary numerals are another way of referring to the “bit” unit of measurement. Binary is a base-2 system, which means that there are only 2 unique values allowed for a binary numeral — 0 or 1. We also know that binary numerals are made up of collections of our friend the “bit”.
The rules for incrementing binary numerics are as follows:
- Binary digits begin as ’0′ –> eg. to represent ’0′, the binary equivalent is ’0′
- Each time we increment beyond ’1′ the left most digit is incremented as well –> eg. to represent ’15′, the binary equivalent is ’1111′
I created a simple Flex app that handles a few of the more handy bitwise calculations. There’s not much to it but if anything it helps for experimenting to see what different values will produce real-time. Click the link to launch…
Get the Flash player…
Supported Bitwise operands and typical usages:
- & — AND (And — Useful when masking)
- ~ – NOT (Inverse — Useful when you need to switch all bits to their counterparts)
- | — OR (Or — Useful when setting flags)
- ^ — XOR (Exclusive Or)
- << — Shift Left
- >> — Shift Right
- >>> — Unsigned Shift Right
- <<< — Unsigned Shift Left
Further optimization:
- Avoid mixing data types.
- Use Signed Integers (int) for everything possible (e.g. counting variables, array access..).
- Use Number if you need precision.
- Use signed integers (int) only for ARGB color values.
- Avoid using uints for counting variables or arithmetic expressions.
Additional Reference:
