amaranth/nmigen/utils.py
whitequark 2f9dab361f {,_}tools→{,_}utils
In context of nMigen, "tools" means "parts of toolchain", so it is
confusing to have a completely unrelated module also called "tools".
2019-10-13 18:53:38 +00:00

22 lines
460 B
Python

__all__ = ["log2_int", "bits_for"]
def log2_int(n, need_pow2=True):
if n == 0:
return 0
r = (n - 1).bit_length()
if need_pow2 and (1 << r) != n:
raise ValueError("{} is not a power of 2".format(n))
return r
def bits_for(n, require_sign_bit=False):
if n > 0:
r = log2_int(n + 1, False)
else:
require_sign_bit = True
r = log2_int(-n, False)
if require_sign_bit:
r += 1
return r