Last active
June 17, 2024 02:41
-
-
Save GaryLee/2739c59dd4373a679c32f27a495cd698 to your computer and use it in GitHub Desktop.
Parse verilog number literal.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def parse_verilog_number(s): | |
"""Parse a verilog number literal to the tuple (sign, bits, base, value). | |
sign: 1 for postive, -1 for negative. | |
bits: The bits token in the number literal. | |
base: The base of number(2, 10 or 16). | |
value: The value token. | |
""" | |
base_token = {'b': 2, 'd': 10, 'h': 16} | |
pattern = re.compile(r"""(?P<sign>[\-\+])?(?P<define>\`)?(?P<bits>[\w]+)?\'((?P<base2>[bB])(?P<value2>[01]+)|(?P<base10>[dD])(?P<value10>\d+)|(?P<base16>[hH])(?P<value16>[0-9a-fA-F]+)|(?P<value>\d+))""") | |
m = pattern.match(s) | |
assert m, ValueError(f"`{s}` is not a valid format of verilog number.") | |
sign = -1 if m.group("sign") == '-' else 1 | |
bits = '`' + m.group("bits") if m.group('define') else m.group("bits") | |
base = m.group("base2") or m.group("base10") or m.group("base16") or 'd' | |
value = m.group("value2") or m.group("value10") or m.group("value16") | |
return sign, bits, base_token[base.lower()], value | |
def to_int(s): | |
"""Convert verilog number literal to number.""" | |
sign, _, base, value = parse_verilog_number(s) | |
return sign * int(value, base) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment