Set all odd bits of a number | Efficient CPP 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 atsame 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 code
#include <iostream> NEW_LINE using namespace std ; int getmsb ( int n ) { n |= n >> 1 ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; return ( n + 1 ) >> 1 ; } int getevenbits ( int n ) { n = getmsb ( n ) ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; if ( ( n & 1 ) == 0 ) n = n >> 1 ; return n ; } int setalloddbits ( int n ) { return n | getevenbits ( n ) ; } int main ( ) { int n = 10 ; cout << setalloddbits ( n ) ; return 0 ; }