Topic : Bit-wise Logical Operators
Author : GHA
Page : << Previous 2  
Go to page :


  BYTE sign = 0;

      for (int i=0; i<x.length(); i++) {
        if (sign == 0)
          sum += x[i];
        else
          sum -= x[i];

        sign ^= 1;      // Toggel sign
      }

      return sum;
   }


C++ also offers left and right shift operators. They use the same symbols, << and >>. as the stream insertion and extraction operators. (In fact, the stream insertion and extraction operators are overloaded shift operators.) The format is illistrated below:

   WORD a, b, x, y;
   ...
   x = a << 8;      // x = value in a, shifted left by 8 bits
   y = b >> k;      // y = value in b, shifted right by k bits

Bits shifted out of range are lost, and new bits shited into range are set to 0. For example:

    11111111 00010001
<< 11111111 11111111
    -----------------
    11111110 00100010

Or, in hex representation:

   0xFF11 << 1 = 0xFE22
The shift operator can be used in compound assignments. The following function counts the number of set bits in a word and uses the >>= operator to shift the tested word:

   int BitsInWord(WORD w) {
     // Returns the number of set bits in w.
     int count = 0;

     while (w) {
       if (w & 0x0001)
         count ++;
       w >>= 1;
     }

     return count;
   }


In the following example, an array of words represents pixels in one horizontal scan line in an image: 1 stands for black and 0 for white. The HorizBorders(...) function effeciently white out all black pixels that are not on the border, that is, the ones with both left and right neighbors.

   void HorizBorders(const gvector<WORD> &pix, gvector<WORD> &pix1) {
     //Eliminates inner pixels (that have both a left and a right
     // neighbor) in a horizontal scan line, represented by bits in
     // the pix array.  Places result in pix1.

     WORD lword, rword;

     for (int i=0; i<pix.length(); i++) {
       lword = pix[i] >> 1;      // Left neighbors;
       if (i > 0)         //   fix the leftmost bit
         lword |= pix[i-1] << 15;   //   from previous word

       rword = pix[i] << 1;      // Right neighbors;
       if (i < n-1)         //   fix the rightmost bit
         rword |= pix[i+1] << 15;   //   from the next word

       pix1[i] = pix[i]  & ~(lword & rword);
     }
   }


Bitwise operators and shifts are very economical-they are usually compiled into one CPU instruction.


Page : << Previous 2