Forum Discussion

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

bit shifting arithmetic

Hi there!

I am trying to get my around some binary arithmetic.

Basically, I don't want to deal with floating points, so I have a problem that was originally

400 * 0.0615 = 24.6

to this

(400*615) >> 4 = 24.6

Except in binary, it doesn't work like this?

for instance,

10 -> 1010

100 -> 1100100

I can't shift it over by simply doing 100 >> 1;

Please help!

Thanks in advance.

6 Replies

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

    --- Quote Start ---

    (400*615) >> 4 = 24.6

    Except in binary, it doesn't work like this?

    --- Quote End ---

    You need to decide. Thinking in base 10, or thinking in base 2. Since you want to do it with simple logic, go with base 2.

    Your 'equation' listed above first multiplies by 10^4, then divides by 2^4. That ain't gonna work. Instead of multiplying .0615 by a power of 10, multiply by a power of two (enough to make it an integer), do the math, then shift it back down (divide) by the same power of 2. (or leave it shifted up in preparation for whatever you're going to do next.)
  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    Thanks for the response! That's actually part of the problem because I haven't wrapped my head around thinking in base 2 yet :)

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

    bit shifting is only useful for multiplies when you have only a few 2^n coefficients. for example:

    0.75 = 0.5 (2^-1) + 0.25(2^-2)

    so 5 x 0.75 = 5x0.5 + 5x0.25

    When you have more than a couple, it is more sensible to use a multiplier instead because it can calculate results faster than a large adder chain.
  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    Division is best avoided on FPGAs. If you can, it is usually much cheaper and faster to multiply by 1/n rather than divide by n. (assuming you can calculate 1/n via some other means (on a CPU, inside a lookup table etc)

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

    Back to your original example:

    --- Quote Start ---

    Basically, I don't want to deal with floating points, so I have a problem that was originally

    400 * 0.0615 = 24.6

    to this

    (400*615) >> 4 = 24.6

    --- Quote End ---

    Instead of multiplying 0.0615 by 10000, multiply by a power of 2. For example:

    = 400 * (0.0615 * 2^16) >> 16

    = 400 * 4030 >> 16

    = 1612000 >> 16

    = 24

    If you want to avoid floats and still have fractional values, you will have to use fixed point.