how to situate a variable in C language

December 6, 2010 at 11:10:37
Specs: Windows XP
i want to situate but not to overflow a vaiable in C e.g. variables a, b, c are 16-bit long, i want compute c= a*b. Let a=64k, b=64k, I expect c keeps the MSB 16 bits of the multilication resultes. Thanks!

See More: how to situate a variable in C language

Report •


#1
December 6, 2010 at 12:45:13
If you multiply 64K x 64k you are always going to get an overflow unless c is a 32 bit integer. There is no CPU that I know of that will discard LSB when it encounters an overflow condition.

If you only want the 16 most significant bits you can put the answer into a 32 bit variable and then Shift right without carry 16 times. This will discard the first 16 bits leaving only the last 16 bits present.

Stuart


Report •

#2
December 7, 2010 at 07:42:27
Thanks. I have to use 16-bit long variable in a low-end DSP. I tried to use multiple intermediate variables to help the processing. Each intermediate variable is also 16-bit long. I divided each original variables to high 8-bits and low 8-bits and stored them in two variables. Then there are 4 combinations of the multilication of which the results are stored in 4 intermiate variables. Right shift the the lower intermiate variables 8 bits, then add it to the high one (8 bit higher). Repeat this until the 2nd highest one. I got the 16-bit MSB.

Report •

#3
December 7, 2010 at 09:01:22
Thats one way of doing it. Similar to doing 64 bit arithmetic on a 32 bit computer.

Stuart


Report •

Related Solutions


Ask Question