Programmable Devices
CPLDs, FPGAs, SoC FPGAs, Configuration, and Transceivers
20688 Discussions

bit shifting arithmetic

Altera_Forum
Honored Contributor II
1,436 Views

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.
0 Kudos
6 Replies
Altera_Forum
Honored Contributor II
462 Views

 

--- 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.)
0 Kudos
Altera_Forum
Honored Contributor II
462 Views

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

0 Kudos
Altera_Forum
Honored Contributor II
462 Views

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.
0 Kudos
Altera_Forum
Honored Contributor II
462 Views

thanks. i decided to use division instead :)

0 Kudos
Altera_Forum
Honored Contributor II
462 Views

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)

0 Kudos
Altera_Forum
Honored Contributor II
462 Views

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.
0 Kudos
Reply