forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrotate_bits.py
More file actions
70 lines (60 loc) · 1.78 KB
/
Copy pathrotate_bits.py
File metadata and controls
70 lines (60 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"""
Author : Basuki Nath
Date : 2025-10-04
Bit rotation helpers for 32-bit unsigned integers.
"""
def rotate_left32(x: int, k: int) -> int:
"""
Rotate the lower 32 bits of x left by k and return result in 0..2**32-1.
>>> rotate_left32(1, 1)
2
>>> rotate_left32(1, 31)
2147483648
>>> rotate_left32(0x80000000, 1)
1
>>> rotate_left32(0x12345678, 4)
591751041
>>> rotate_left32(-1, 3)
Traceback (most recent call last):
...
ValueError: x must be a non-negative integer
>>> rotate_left32(1, -1)
Traceback (most recent call last):
...
ValueError: k must be non-negative
"""
if not isinstance(x, int) or x < 0:
raise ValueError("x must be a non-negative integer")
if not isinstance(k, int) or k < 0:
raise ValueError("k must be non-negative")
mask = (1 << 32) - 1
k &= 31
return ((x << k) & mask) | ((x & mask) >> (32 - k))
def rotate_right32(x: int, k: int) -> int:
"""
Rotate the lower 32 bits of x right by k and return result in 0..2**32-1.
>>> rotate_right32(2, 1)
1
>>> rotate_right32(1, 1)
2147483648
>>> rotate_right32(0x12345678, 4)
2166572391
>>> rotate_right32(-1, 1)
Traceback (most recent call last):
...
ValueError: x must be a non-negative integer
>>> rotate_right32(1, -3)
Traceback (most recent call last):
...
ValueError: k must be non-negative
"""
if not isinstance(x, int) or x < 0:
raise ValueError("x must be a non-negative integer")
if not isinstance(k, int) or k < 0:
raise ValueError("k must be non-negative")
mask = (1 << 32) - 1
k &= 31
return ((x & mask) >> k) | ((x << (32 - k)) & mask)
if __name__ == "__main__":
import doctest
doctest.testmod()