Review:   How to clear the bit at position k

  • The CLRBIT(x, k) operation: (clears the bit at position k in x)

                                   position k
                                       |
                                       V
     Before CLRBIT(x,k):    x = 1010...?...1101 
     After  CLRBIT(x,k):    x = 1010...0...1101  

  • Solution:   apply an AND operation to clear the bit at position k:

             x = 1010...?...1101  
       pattern = 111..11011..111
                ---------------- AND
             x = 1010...0...1101    (? AND 0 = 0 and y AND 1 = y)
    
       CLRBIT(x,k)x = x & pattern

We can use a shift operation to construct the pattern 111..11011..111

Algorithm to clear the bit at position k

  • How to construct the pattern:

                   position k
                       |
                       V
      pattern = 111..11011..111

  • We start with the following binary pattern:

      000....0....0001   (= 1 in decimal)
    

  • Then shift the pattern k positions to the left and flip the bits:

      000..00100..0000   (= 1 << k )
      111..11011..1111   (= ~(1 << k) )
    

Algorithm to clear the bit at position k

  • The CLRBIT(x, k) operation: (clears the bit at position k in x)

                                   position k
                                       |
                                       V
     Before CLRBIT(x,k):    x = 1010...?...1101 
     After  CLRBIT(x,k):    x = 1010...0...1101  

  • Solution:   apply an AND operation to clear the bit at position k:

             x = 1010...?...1101  
       pattern = 111..11011..111(~(1 << k ))
                ---------------- AND
             x = 1010...0...1101    (? AND 0 = 0 and y AND 1 = y)
    
       CLRBIT(x,k)x = x & (~(1 << k )) 

Note: C programmers often define CLRBIT as a macro:   #define CLRBIT(x,k) (x &= ~(1 << k))