Clear Bit
by Isai Damier

#======================================================================
# Author: Isai Damier
# Title: Clear Bit
# Project: geekviewpoint
# Package: algorithms
#
# Statement:
#   Given a bit sequence x, clear the kth bit; where the zeroth
#   (0th) bit is the least significant (rightmost) bit.
#
# Sample Input: integer representation of bit sequence 0010010010
# Sample Output: 0010010000 after clearing the 1st bit
#
# Technical Details:
#   Let x = 0010010010. Then only the 1st, 4th, and 7th bits are set.
#   Therefore, clearBit(x,1) would return 0010010000; whereas
#   clearBit(x,3) would have no effect and so would return 0010010010.
#
#   clearBit is a three steps operation:
#
#   0] Using the shift-left operator <<, create a bit sequence
#     where only the kth bit is set.
#
#   1] Take the negation of the sequence in step_0. This effectively
#     creates a sequence where all bits are set except the kth bit.
#
#   2] Take the bitwise AND of x and the sequence in step_1. In digital
#     logic a&1 is equal to 1 whereas a&0 is equal to 0. Therefore, this
#     operation force clear the kth bit while leaving the other bits
#     unchanged.
#
#====================================================================== 
 def clearBit( x, kth ):
  return ( x & ~( 1 << kth ) )
import unittest
from algorithms import bitwise as bits

class Test( unittest.TestCase ):

    def testClearBit( self ):

      x = int( "0010010010", 2 )
      a = int( "0010010000", 2 )
      b = int( "0010000010", 2 )
      c = int( "0000010010", 2 )

      self.assertEqual( x, bits.clearBit( x, 0 ) )
      self.assertEqual( a, bits.clearBit( x, 1 ) )
      self.assertEqual( b, bits.clearBit( x, 4 ) )
      self.assertEqual( c, bits.clearBit( x, 7 ) )