Set all even bits of a number | Efficient CPP program to set all even bits of a number ; return msb set number ; set all bits ; return msb increment n by 1 and shift by 1 ; return even seted number ; get msb here ; generate even bits like 101010. . ; if bits is odd then shift by 1 ; return even set bits number ; set all even bits here ; take or with even 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 ) n = n >> 1 ; return n ; } int setallevenbits ( int n ) { return n | getevenbits ( n ) ; } int main ( ) { int n = 10 ; cout << setallevenbits ( n ) ; return 0 ; }