Truth Table

XYX & YX | YX ^ Y
00000
01011
10011
11110

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.

1’s and 2’s Complement

  • 1’s complement means negation(not) of any number
  • get 2’s complement by adding 1 to 1’s complement
Original number:   0000 0101  (5)
1's complement:    1111 1010

Add 1
2's complement:    1111 1011

2's complement = (~binary number) + 1

Questions

Q1. 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))

Set i’th bit: data = data | (1<<bit) Clear i’th bit: data = data & ~(1<<bit)

Q2. 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)

Q3. Clear left most set bit

result = n & (n-1)

eg. n=40
40    101000
39    100111
res   100000

Can be used to check if given number is power of 2. Because it has only 1 set bit (n & (n - 1) == 0)

Q4. 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;
}

Q5. 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;
}