#======================================================================
# Author: Isai Damier
# Title: Test Bit
# Project: geekviewpoint
# Package: algorithms
#
# Statement:
# Given a bit sequence, indicate whether the kth bit is set.
# The zeroth (0th) bit is the least significant
# (rightmost) bit.
#
# Sample Input: 0010010010, 4
# Sample Output: true
#
# Technical Details: Let x = 0010010010. Then only the 1st, 4th,
# and the 7th bits are set. Therefore, testBit(x,4) would return
# TRUE while testBit(x,2) would return FALSE.
#
# testBit is a three steps operation:
# step_1] Using the shift-left operator << create a bit
# sequence where only the kth bit is set.
# step_2] Take the bitwise AND of x and the sequence in step_1.
# This operation will force clear all the bits in x; except
# the kth bit. It leaves the kth bit unchanged.
# step_3] Compare the result of step_2 to zero (0). This step
# is effectively comparing the kth bit to zero.
#======================================================================
def testBit( x, kth ):
return ( x & 1 << kth ) != 0
import unittest
from algorithms import bitwise as bits
class Test( unittest.TestCase ):
def testTestBit( self ):
s = "0010010010";
length = len( s ) - 1;
x = int( s, 2 );
for i in range( length, 0, -1 ):
if ( s[i] == '1' ):
self.assertTrue( bits.testBit( x, length - i ) )
else:
self.assertFalse( bits.testBit( x, length - i ) )