This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

unexpected results in integer arithmetics

Hello experts,

to avoid a division, I use integer arithmetics. The unsigned int x which is in the range of 2000 is first multiplied by a number s which is 2048 plus/minus 1000 and then shifted by 11 digits which should replace a division by 2048.

unsigned int  near x;
unsigned int  s

 x = ( (unsigned long) x * (unsigned long) s ) >> 11 ;

For testing I used s=2048. The result should be (x*2048)>>11 = x, but what I get as a result is about 30 times too big, and all results for different values of x are multiples of 0x20.

Type casting problem?

Please help, I run out of ideas.

Parents
  • Oh, one other thing. If you must bit-shift, C only guarantees that you will pull in zeros when left shifting. Right shifting is implementation defined. So, in your example, you should AND off the top 11 bits of the result before using it.

Reply
  • Oh, one other thing. If you must bit-shift, C only guarantees that you will pull in zeros when left shifting. Right shifting is implementation defined. So, in your example, you should AND off the top 11 bits of the result before using it.

Children