Skip to content

Commit f77074a

Browse files
Create swap_all_odd_and_even_bits.py
1 parent 572de4f commit f77074a

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
def swap_odd_even_bits(num):
2+
# Get all even bits
3+
even_bits = num & 0xAAAAAAAA # 0xAAAAAAAA is a 32-bit number with all even bits set to 1
4+
5+
# Get all odd bits
6+
odd_bits = num & 0x55555555 # 0x55555555 is a 32-bit number with all odd bits set to 1
7+
8+
# Right shift even bits by 1 and left shift odd bits by 1 to swap them
9+
even_bits >>= 1
10+
odd_bits <<= 1
11+
12+
# Combine the swapped even and odd bits
13+
result = even_bits | odd_bits
14+
15+
return result
16+
17+
# Example usage:
18+
num = 23 # Binary: 10111
19+
swapped_num = swap_odd_even_bits(num) # Result: 43 (Binary: 101011)
20+
print(swapped_num)
21+
22+
# In this code:
23+
24+
# 1. We use bitwise AND operations to separate the even bits (0, 2, 4, 6, etc.) and odd bits (1, 3, 5, 7, etc.) in the input number.
25+
# 2. We then right-shift the even bits by 1 position and left-shift the odd bits by 1 position to swap them.
26+
# 3. Finally, we combine the swapped even and odd bits using a bitwise OR operation to obtain the final result.

0 commit comments

Comments
 (0)