Wednesday, October 27, 2010

Bitwise Operators - Uses

  • Efficient storage.
    • Status bits. Eg, Mouse event key mask.
    • Eg, representing Connect-Four board.
    • Packing or unpacking values into a single int/long.
      A common use of the bitwise operators (shifts with ands to extract values and ors to add values) is to work with multiple values that have been encoded in one int. Bit-fields are another way to do this. For example, let's say you have the following integer variables: age (range 0-127), gender (range 0-1), height (range 0-128). These can be packed and unpacked into/from one short (two-byte integer) like this (or many similar variations).
      //define the variables 

      int   age, gender, height;
      short packed_info;
      . . .
      // packing
      packed_info = (((age << 1) | gender) << 7) | height;
      . . .
      // unpacking
      height = packed_info & 0x7f;
      gender = (packed_info >>> 7) & 1;
      age = (packed_info >>> 8);

    • Setting flag bits
      Some library functions take an int that contains bits, each of which represents a true/false (boolean) value. This saves a lot of space and can be fast to process.

  • Efficient computation

    • On some (esp old) machines, shifting is faster than multiplying or dividing by powers of two.
      y = x << 3;        // Assigns 8*x to y.
      y = (x << 2) + x; // Assigns 5*x to y.

    • Flipping between on and off with xor

    • Sometimes xor is used to flip between 1 and 0.

      x = x ^ 1;      // Or the more cryptic x ^= 1;

      In a loop that will change x alternately between 0 and 1.

  • Problems

No comments:

Post a Comment

Chitika