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