Set Bit
by Isai Damier, Android Engineer @ Google
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #====================================================================== # Author: Isai Damier # Title: Set Bit # Project: geekviewpoint # Package: algorithms # # Statement: # Given a bit sequence x, set the kth bit; where the zeroth (0th) bit # is the least significant (rightmost) bit. # # Sample Input: 0010010010 # Sample Output: 0010010011 # # Description: # # Technical Details: Let x = 0010010010. Then only the 1st, 4th, # and the 7th bits are set. The function setBit(x,0) would # return 0010010011. # # setBit is a two 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 OR of x and the sequence in step_1. #====================================================================== def setBit( x, kth ): return x | ( 1 << kth ) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import unittest from algorithms import bitwise as bits class Test( unittest.TestCase ): def testSetBit( self ): x = int ( "0010010010" , 2 ) a = int ( "0010010011" , 2 ) b = int ( "0010011010" , 2 ) c = int ( "0110010010" , 2 ) self .assertEquals( a, bits.setBit( x, 0 ) ) self .assertEquals( b, bits.setBit( x, 3 ) ) self .assertEquals( c, bits.setBit( x, 8 ) ) |