Skip to content

Commit be94690

Browse files
NikhithaBandaripre-commit-ci[bot]cclauss
authored
Create swap_all_odd_and_even_bits.py (#10692)
* Create swap_all_odd_and_even_bits.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update swap_all_odd_and_even_bits.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * 6: 00000110 --> 9: 0000100 * Update swap_all_odd_and_even_bits.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent 26ffad9 commit be94690

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
def show_bits(before: int, after: int) -> str:
2+
"""
3+
>>> print(show_bits(0, 0xFFFF))
4+
0: 00000000
5+
65535: 1111111111111111
6+
"""
7+
return f"{before:>5}: {before:08b}\n{after:>5}: {after:08b}"
8+
9+
10+
def swap_odd_even_bits(num: int) -> int:
11+
"""
12+
1. We use bitwise AND operations to separate the even bits (0, 2, 4, 6, etc.) and
13+
odd bits (1, 3, 5, 7, etc.) in the input number.
14+
2. We then right-shift the even bits by 1 position and left-shift the odd bits by
15+
1 position to swap them.
16+
3. Finally, we combine the swapped even and odd bits using a bitwise OR operation
17+
to obtain the final result.
18+
>>> print(show_bits(0, swap_odd_even_bits(0)))
19+
0: 00000000
20+
0: 00000000
21+
>>> print(show_bits(1, swap_odd_even_bits(1)))
22+
1: 00000001
23+
2: 00000010
24+
>>> print(show_bits(2, swap_odd_even_bits(2)))
25+
2: 00000010
26+
1: 00000001
27+
>>> print(show_bits(3, swap_odd_even_bits(3)))
28+
3: 00000011
29+
3: 00000011
30+
>>> print(show_bits(4, swap_odd_even_bits(4)))
31+
4: 00000100
32+
8: 00001000
33+
>>> print(show_bits(5, swap_odd_even_bits(5)))
34+
5: 00000101
35+
10: 00001010
36+
>>> print(show_bits(6, swap_odd_even_bits(6)))
37+
6: 00000110
38+
9: 00001001
39+
>>> print(show_bits(23, swap_odd_even_bits(23)))
40+
23: 00010111
41+
43: 00101011
42+
"""
43+
# Get all even bits - 0xAAAAAAAA is a 32-bit number with all even bits set to 1
44+
even_bits = num & 0xAAAAAAAA
45+
46+
# Get all odd bits - 0x55555555 is a 32-bit number with all odd bits set to 1
47+
odd_bits = num & 0x55555555
48+
49+
# Right shift even bits and left shift odd bits and swap them
50+
return even_bits >> 1 | odd_bits << 1
51+
52+
53+
if __name__ == "__main__":
54+
import doctest
55+
56+
doctest.testmod()
57+
for i in (-1, 0, 1, 2, 3, 4, 23, 24):
58+
print(show_bits(i, swap_odd_even_bits(i)), "\n")

0 commit comments

Comments
 (0)