Skip to content

Commit 6199c5b

Browse files
committed
feat: add utils.py for helper functions
1 parent f0455f2 commit 6199c5b

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

utils.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
#!/usr/bin/env python3
2+
3+
def bits_le_with_width(i, width):
4+
if i >= 2**width:
5+
return "Failed"
6+
bits = []
7+
while width:
8+
bits.append(i % 2)
9+
i //= 2
10+
width -= 1
11+
return bits
12+
13+
14+
def pow_2(n):
15+
return 1 << n
16+
17+
def is_power_of_two(n):
18+
d = n
19+
k = 0
20+
while d > 0:
21+
d >>= 1
22+
k += 1
23+
if n == 2**(k-1):
24+
return True
25+
else:
26+
return False
27+
28+
def next_power_of_two(n):
29+
assert n >= 0, "No negative integer"
30+
if is_power_of_two(n):
31+
return n
32+
d = n
33+
k = 1
34+
while d > 0:
35+
d >>= 1
36+
k <<= 1
37+
return k
38+
39+
def log_2(x):
40+
"""
41+
Compute the integer part of the logarithm base 2 of x.
42+
43+
Args:
44+
x (int): The number to compute the logarithm of. Must be a positive integer.
45+
46+
Returns:
47+
int: The floor of the logarithm base 2 of x.
48+
49+
Raises:
50+
ValueError: If x is not a positive integer.
51+
"""
52+
if not isinstance(x, int) or x <= 0:
53+
raise ValueError("x must be a positive integer")
54+
55+
result = 0
56+
while x > 1:
57+
x >>= 1 # Bit shift right (equivalent to integer division by 2)
58+
result += 1
59+
return result

0 commit comments

Comments
 (0)