Set all odd bits of a number | Efficient python3 program to set all odd bits number ; return MSB set number ; set all bits including MSB . ; return MSB ; Returns a number of same size ( MSB at same position ) as n and all odd bits set . ; generate odd bits like 010101. . ; if bits is even then shift by 1 ; return odd set bits number ; set all odd bits here ; take OR with odd set bits number ; Driver Program
import math NEW_LINE def getmsb ( n ) : NEW_LINE INDENT n |= n >> 1 NEW_LINE n |= n >> 2 NEW_LINE n |= n >> 4 NEW_LINE n |= n >> 8 NEW_LINE n |= n >> 16 NEW_LINE return ( n + 1 ) >> 1 NEW_LINE DEDENT def getevenbits ( n ) : NEW_LINE INDENT n = getmsb ( n ) NEW_LINE n |= n >> 2 NEW_LINE n |= n >> 4 NEW_LINE n |= n >> 8 NEW_LINE n |= n >> 16 NEW_LINE if ( ( n & 1 ) == 0 ) : NEW_LINE INDENT n = n >> 1 NEW_LINE DEDENT return n NEW_LINE DEDENT def setalloddbits ( n ) : NEW_LINE INDENT return n | getevenbits ( n ) NEW_LINE DEDENT n = 10 NEW_LINE print ( setalloddbits ( n ) ) NEW_LINE