Geeking-out with Bitwise Operations

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) : 10110110

We 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:

http://www.gamedev.net/reference/articles/article1563.asp

About John Pencola

Hello, my name is John Pencola. I can't get enough of exploring new technologies, discussing software principals, creating programs and having fun with interface design. I will share my experiences here and hope Liquid Language adds some useful information to the vast sea that is the web.
This entry was posted in ActionScript 3, Flex 3. Bookmark the permalink.