Swap all odd and even bits in Python
Hello friends in this tutorial, we will learn to swap the odd and even bits of a number and write the code for it in Python.
Now let’s explore how we can do it.
For example: The number 43 can be represented as 0 0 1 0 1 0 1 1 in binary. The bits in bold are at even positions which are 0 1 1 1 and the bits at the odd position are 0 0 0 1.
After swapping the odd and even bits we get 0 0 0 1 0 1 1 1 which is 23.
Let’s see how we can swap the odd-even bits
- Perform bitwise AND operation with hexadecimal 55555555 to extract the odd bits form the number
- Perform bitwise AND operation with hexadecimal AAAAAAAA to extract the even bits form the number
- To shift odd bits to even position, perform left shift << by 1 position
- To shift even bits to odd position, perform right shift >> by 1 position
- Finally, combine both the bits using bitwise OR operator
Program to Swap Odd and Even bits in Python
Following is the code implementation in Python.
# PROGRAM TO SWAP ODD AND EVEN BITS print("Enter the number") num = int(input()) # take input value of num odd_bits = num & 0x55555555 # to extract odd bits of num even_bits = num & 0xAAAAAAAA # to extract even bits of num odd_bits = odd_bits << 1 # to shift odd bits to even position even_bits = even_bits >> 1 # to shift even bits to odd position new_num = odd_bits | even_bits # combining odd and even bits print("Before swapping bits",num) print("After swapping bits",new_num)
Enter the number 43 Before swapping bits 43 After swapping bits 23