Toggle all bits after most significant bit | Returns a number which has all set bits starting from MSB of n ; This makes sure two bits ( From MSB and including MSB ) are set ; This makes sure 4 bits ( From MSB and including MSB ) are set ; Driver code
function setAllBitsAfterMSB ( n ) { n |= n >> 1 ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; return n ; } function toggle ( n ) { n = n ^ setAllBitsAfterMSB ( n ) ; return n ; } let n = 10 ; document . write ( toggle ( n ) ) ;