Review:   How to set the bit at position k to 1

  • The SETBIT(x, k) operation: (sets the bit at position k in x)

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

  • Solution:   apply an OR operation to set the bit at position k:

             x = 1010...?...1101  
       pattern = 000..00100..000
                ---------------- OR
             x = 1010...1...1101    (y OR 0 = y and ? OR 1 = 1)
    
       SETBIT(x,k)x = x | pattern

We can use a shift operation to construct the pattern 000..00100..000

Algorithm to to set the bit at position k

  • How to construct the pattern:

                   position k
                       |
                       V
      pattern = 000..00100..000

  • We start with the following binary pattern:

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

  • Then shift the pattern k positions to the left:

      000..00100..0000   (= 1 << k )
    

Algorithm to to set the bit at position k

  • The SETBIT(x, k) operation: (sets the bit at position k in x)

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

  • Solution:   apply an OR operation to set the bit at position k:

             x = 1010...?...1101  
       pattern = 000..00100..000(1 << k)
                ---------------- OR
             x = 1010...1...1101    (y OR 0 = y and ? OR 1 = 1)
    
       SETBIT(x,k)x = x | (1 << k) 

Note: C programmers often define SETBIT as a macro:   #define SETBIT(x,k) (x |= (1 << k))