Read in KR

Bits and Widths

When working with integer values in SCode, you often need to determine the number of bits required to represent a specific value. For this purpose, SCode provides the min_bits and max_bits_of_list functions.

min_bits

This function returns the minimum number of bits required to represent a given value or the width of a logic signal.

Note that if 0 or 1 is passed as a parameter, it returns 1 because both values can be represented with 1 bit. min_bits is frequently used to define logic with a width sufficient to hold a specific integer value.

The following is an excerpt from the counter_trigger function in core_lib.sh. This function counts up to a given n and generates a single trigger pulse.

def counter_trigger(clk, reset, n): 
    count = logic_unique('ctrg_out[%s]' % min_bits(n)) 
    
    ... 

To count up to n, it is necessary to declare a logic signal with a bit width that can represent n.

max_bits_of_list

The max_bits_of_list function calculates the min_bits for every value in a given list and returns the largest among them.

It is primarily used when declaring logic that must be able to represent any of several different values. The following code is an excerpt from tbl_pattern in core_lib.sh:

def tbl_pattern(clk, n, pattern_data): 
    pattern = logic_unique('pattern[%s]' % max_bits_of_list(pattern_data))

If pattern_data is a list, this code declares logic with a width sufficient to represent any value in the list.

← All posts