Bitwise Operators

Truth Table X Y X & Y X | Y X ^ Y 0 0 0 0 0 0 1 0 1 1 1 0 0 1 1 1 1 1 1 0 Points to Remember The left-shift and right-shift operators should not be used for negative numbers Left Shift(<<) just means multiply by 2. Similarly >> results division by 2. XOR results 0 if both bits are same. So a^1=~a , a^0=a and a^a=0. Questions How to toggle or flip a particular bit in a number? To toggle any bit in a variable, Use (^) exclusive OR operator. #define togglebit(data, bit) (data* = data ^ (1<<bit)) Write MACRO to Swap the bytes in 16bit Integer Variable. #define ByteSwap16(Value) ((Value & 0x00FF) << 8) | ((Value & 0xFF00) >> 8) #define ByteSwap32(Value) ((Value & 0x000000FF) << 24) | ((Value & 0x0000FF00U) << 8) | ((Value & 0x00FF0000U) >> 8) | ((Value & 0xFF000000U) >> 24) Count the number of set bits in a number unsigned int countSetBits( unsigned int number ) { unsigned int count = 0; while( number != 0) { count++; number &= (number-1); } return count; } Swap 2 bits of given integer int swapBits(unsigned int n, unsigned int p1, unsigned int p2) { unsigned int bit1 = (n >> p1) & 1; /* Move p1'th to rightmost side */ unsigned int bit2 = (n >> p2) & 1; /* Move p2'th to rightmost side */ unsigned int x = (bit1 ^ bit2); /* XOR the two bits */ /* Put the xor bit back to their original positions */ x = (x << p1) | (x << p2); /* XOR 'x' with the original number so that the two sets are swapped */ unsigned int result = n ^ x; }

February 19, 2025 · 2 min