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
  • Hello,
    I tried this on my system and the results were fine. The assembly code is;

    
    s is assigned to R5
    x is assigned to R4
    
     MOV   R5, DPP2:s
     MOV   R4, DPP2:x
    
     MULU  R4, R5          ;x*s
     MOV   R5, MDH
     MOV   R4, MDL
     MOV   R6, R5
     SHR   R4, #0x0B       ;>>11 (32-bit)
     SHL   R6, #0x05
     OR    R4, R6
     MOV   DPP2:x, R4
    

    This is pretty good code except for the extraneous loading of R5 from MDH. Turn on the assembly code option in the listing tab of the project settings and see what you get.

    Best Luck
    Scott


Reply
  • Hello,
    I tried this on my system and the results were fine. The assembly code is;

    
    s is assigned to R5
    x is assigned to R4
    
     MOV   R5, DPP2:s
     MOV   R4, DPP2:x
    
     MULU  R4, R5          ;x*s
     MOV   R5, MDH
     MOV   R4, MDL
     MOV   R6, R5
     SHR   R4, #0x0B       ;>>11 (32-bit)
     SHL   R6, #0x05
     OR    R4, R6
     MOV   DPP2:x, R4
    

    This is pretty good code except for the extraneous loading of R5 from MDH. Turn on the assembly code option in the listing tab of the project settings and see what you get.

    Best Luck
    Scott


Children
More questions in this forum