-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathutils.py
59 lines (49 loc) · 1.15 KB
/
utils.py
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
#!/usr/bin/env python3
def bits_le_with_width(i, width):
if i >= 2**width:
return "Failed"
bits = []
while width:
bits.append(i % 2)
i //= 2
width -= 1
return bits
def pow_2(n):
return 1 << n
def is_power_of_two(n):
d = n
k = 0
while d > 0:
d >>= 1
k += 1
if n == 2**(k-1):
return True
else:
return False
def next_power_of_two(n):
assert n >= 0, "No negative integer"
if is_power_of_two(n):
return n
d = n
k = 1
while d > 0:
d >>= 1
k <<= 1
return k
def log_2(x):
"""
Compute the integer part of the logarithm base 2 of x.
Args:
x (int): The number to compute the logarithm of. Must be a positive integer.
Returns:
int: The floor of the logarithm base 2 of x.
Raises:
ValueError: If x is not a positive integer.
"""
if not isinstance(x, int) or x <= 0:
raise ValueError("x must be a positive integer")
result = 0
while x > 1:
x >>= 1 # Bit shift right (equivalent to integer division by 2)
result += 1
return result