Swap all odd and even bits | Function for swapping even and odd bits ; Get all even bits of x ; Get all odd bits of x ; Right shift even bits ; Left shift odd bits ; Combine even and odd bits ; 00010111 ; Output is 43 ( 00101011 )
def swapBits ( x ) : NEW_LINE INDENT even_bits = x & 0xAAAAAAAA NEW_LINE odd_bits = x & 0x55555555 NEW_LINE even_bits >>= 1 NEW_LINE odd_bits <<= 1 NEW_LINE return ( even_bits odd_bits ) NEW_LINE DEDENT x = 23 NEW_LINE print ( swapBits ( x ) ) NEW_LINE