Forum Discussion

Altera_Forum's avatar
Altera_Forum
Icon for Honored Contributor rankHonored Contributor
13 years ago

Rounding algorithm for 2's complement number

Hi,

Can someone provide me with the rounding algorithm for 2's complement number. rounding opertation (round to nearest) is hard to get for negative numbers in 2's complment. Help me with the solution

sskhati

1 Reply

  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    --- Quote Start ---

    Hi,

    Can someone provide me with the rounding algorithm for 2'scomplement number. rounding opertation (round to nearest) is hard to get for negative numbers in 2's complment. Help me with the solution

    sskhati

    --- Quote End ---

    This example should help (assuming data is 32 bits signed, to be rounded to 16 bits using nearest as defined in Matlab):

    lsb <= '0' & data(15);

    data_int <= signed(data(32 downto 16)) + signed(lsb);

    data_rounded <= data_int(15 downto 0);

    you will need to take care of type conversions

    alternatively you can add constant '1' to data(32 downto 15) then chop off.

    data_int <= signed(data(32 downto 15)) + 1;

    data_rounded <= data_int(16 downto 1);