diff --git a/litex/gen/fhdl/verilog.py b/litex/gen/fhdl/verilog.py index d8b0dad619..bebcd8fd9f 100644 --- a/litex/gen/fhdl/verilog.py +++ b/litex/gen/fhdl/verilog.py @@ -29,6 +29,7 @@ from litex.gen import LiteXContext from litex.gen.fhdl.namer import build_signal_namespace from litex.gen.fhdl.hierarchy import LiteXHierarchyExplorer +from litex.gen.format import format_constant from litex.build.tools import get_litex_git_revision @@ -165,10 +166,10 @@ def _generate_hierarchy(top): # Print Constant ----------------------------------------------------------------------------------- def _generate_constant(node): - return "{sign}{bits}'d{value}".format( + return "{sign}{bits}'{value}".format( sign = "" if node.value >= 0 else "-", bits = str(node.nbits), - value = abs(node.value), + value = format_constant(abs(node.value), verilog=True), ), node.signed # Print Signal ------------------------------------------------------------------------------------- diff --git a/litex/gen/format.py b/litex/gen/format.py new file mode 100644 index 0000000000..b218ff4b45 --- /dev/null +++ b/litex/gen/format.py @@ -0,0 +1,34 @@ + +def format_constant(c, verilog:bool = False): + """Automatically format constants based on type and value. + + If the argument `verilog` isn't provided, a 'c' style constant is generated. + + Integer constants are formatted as decimal or hexadecimal depending on which + value will give the clearest representation, as indicated by the least unique + numbers in the string representation. + + NOTE: Integers below 100 are always formatted as decimal. + + Parameters + ---------- + c : any + constant to format. Only integer constants are formatted. + + verilog : bool, optional + Format for verilog (default is False) + + Raises + ------ + None + """ + + if not isinstance(c, int): + return c + + d, x = f"{c:d}", f"{c:x}" + decimal = abs(c) < 100 or len(set(d)) <= len(set(x)) + if verilog: + return "d" + d if decimal else "h" + x + else: + return d if decimal else "0x" + x diff --git a/litex/soc/integration/export.py b/litex/soc/integration/export.py index 5835e7c222..c89fce557c 100644 --- a/litex/soc/integration/export.py +++ b/litex/soc/integration/export.py @@ -28,6 +28,7 @@ from migen import * +from litex.gen.format import format_constant from litex.soc.interconnect.csr import CSRStatus from litex.soc.integration.soc import SoCRegion @@ -181,7 +182,7 @@ def get_soc_header(constants, with_access_functions=True): value = "\"" + value + "\"" ctype = "const char *" else: - value = str(value) + value = format_constant(value) ctype = "int" r += "#define "+name+" "+value+"\n" if with_access_functions: