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 )