Toggle all bits after most significant bit | Java program to toggle set bits starting from MSB ; 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
class GFG { static int setAllBitsAfterMSB ( int n ) { n |= n >> 1 ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; return n ; } static int toggle ( int n ) { n = n ^ setAllBitsAfterMSB ( n ) ; return n ; } public static void main ( String arg [ ] ) { int n = 10 ; n = toggle ( n ) ; System . out . print ( n ) ; } }