Skip to content

Commit

Permalink
utils: backport ceil_log2 and exact_log2.
Browse files Browse the repository at this point in the history
  • Loading branch information
wanda-phi authored and whitequark committed Feb 19, 2024
1 parent 8450104 commit d562d0e
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion amaranth/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,28 @@
__all__ = ["log2_int", "bits_for"]
import operator

__all__ = ["ceil_log2", "exact_log2", "log2_int", "bits_for"]


def ceil_log2(n):
"""Returns the integer log2 of the smallest power-of-2 greater than or equal to `n`.
Raises a `ValueError` for negative inputs."""
n = operator.index(n)
if n < 0:
raise ValueError("{n} is negative")
if n == 0:
return 0
return (n - 1).bit_length()


def exact_log2(n):
"""Returns the integer log2 of `n`, which must be an exact power of two.
Raises a `ValueError` if `n` is not a power of two."""
n = operator.index(n)
if n <= 0 or (n & (n - 1)):
raise ValueError("{n} is not a power of 2")
return (n - 1).bit_length()

def log2_int(n, need_pow2=True):
if n == 0:
Expand Down

0 comments on commit d562d0e

Please sign in to comment.