Friday, July 16, 2010

Bitwise Operators in C++

Bitwise operators let you manipulate individual bits in a value; they operate on the bits on integer values Left shift operator shifts all bits to the left Bitwise negation turns each 1 to a 0 and each 0 to a 1 Value <<> Value is the value to be shifted and shift is the number of bits to shift. The vacated places are filled with zero and bits past the end are discarded Shifting one bit position is equivalent to multiplying the value by 2; shifting two bits is equivalent to multiplying by 2^2 Value <<= shift Value >> shift for right shifting Shifting one place to the right is equivalent to integer division by 2
  • The ~(Called: Complement, Ones complement, NOT, bit flip, invert) operator converts each individual bit to its opposite
  • The |(Bitwise OR) operator combines bits
  • The ^(Bitwise XOR) operator acts as XOR
  • The &(Bitwise AND) operator acts as AND between two bits
Caution: To find out if any of values i or j is zero we can use the test ((i && j) == 0) but we can't use ((i & j) == 0) for example 100 and 010 pass ( ( i & j ) == 0 ) but neither is zero
 #include  #include  #include  #include  #include   void ShowNumber(const char* desc, unsigned int number) {   std::bitset     bitSet(number);   std::cout << value =" 13;">> 3", value >> 3);    int value2 = 15;   ShowNumber("15", value2);   ShowNumber("-15", -15);    ShowNumber("15 | 13", value2 | value);   ShowNumber("15 & 13", value2 & value);   ShowNumber("~15", ~value2);   ShowNumber("15 ^ 13", value2 ^ value);    //How to determine if a number is a power of two (2,4,8,16,...)   ShowNumber("32 & (32 - 1) must be 0", 32 & (32 - 1));    //Another way to determine a number is a power of two   ShowNumber("18 & -18 is not equal to 18", 18 & -18);   ShowNumber("32 & -32 is equal to 32", 32 & -32);    //Multiply a number by 2 without using multiplication   ShowNumber("13 * 2 without multiplicatoin", 13 << 7n =" (8" isetvalue =" 15;" isetbitcount =" 0;" isetvalue =" iSetValue">> 1;   }    std::cout << "Total count is "      <<>

No comments:

Post a Comment