Search code examples
vhdl

What is the minimum number of bits I need to express a n-bit, signed std_logic_vector in VHDL?


I'm new to VHDL and am trying to find a way to take a n bit (stored as a generic) signed number and truncate it to a form that requires the minimum number of bits.

For example, if I have 5 as its 8 bit signed number (stored in a std_logic_vector of length 8) 00000101, I'd like to make a function to return 0101 as a std_logic_vector. Any ideas on how I can accomplish this?


Solution

  • Since you have specified that you're using a signed value, you may want to use the signed type (from the numeric_std library) instead of the more generic std_logic_vector.

    If your number is a compile time constant, you can write a function starting from the leftmost bit (in a for loop for example) that counts how many identical bits it sees, then returns signed_input(8-result downto 0). The issue with this is that as a compile time constant, there isn't much advantage in removing the redundant bits. The whole vector will be optimized away in synthesis.

    You might want to include special cases to make the result at least 1 bit (0 technically doesn't need any bits to represest) or 2 bits (-1 only needs the sign bit to distinguish it from 0) depending on how you want to use your signed type value.

    If your number is a real signal (the value changes during operation), you can still count the number of identical bits from the left, but variable location slicing of the vector will be iffy. Are you trying to pack the most of several numbers into a fixed bit width? Doing that will synthesize into multiplexers for each bit as well as the LUTs used for calculating the number of redundant bits for each of the numbers.