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

A compilation problem

In my codes, I got a strange result following. I compilerd by C51 9.03, and C51 9.60 is as the same result. That doesn't fit my logic. In the comment after the code is the value obtained when debugging

unsigned char aa,bb,cc,dd;
aa = 0xab;
bb = 0xcd;
cc = (aa+bb)%255;    //cc=0x79
dd = (unsigned char)((aa+bb)%255);  //dd=0x78

The following  is the disassembly code. The right is the option of C51.

In fact, cc and dd should be 0x79. I use parentheses to clearly indicate the operation priority order: first calculate the sum, calculate the modulus, and then cast to unsigned char.

I tried in VC2010, TI CCS3.3, both can get the correct result 0x79, that is to say, cc=0x79 and dd=0x79.

Thank you for your attention.

Parents
  • I think you have found a compiler issue. I was able to reproduce it. Do you have a valid license? If yes, it would be good if you would raise a support case so that we can notify you once this issue is fixed.

    The expression "(unsigned char)((aa+bb)%255)" is calculated only 8 bit wide because of the cast to 'unsigned char' (which is wrong). So in this case 0xab+0xcd is calculated to 0x78 instead of 0x0178. The modulo 255 then calculates 0x78 instead of 0x79. I have forwarded this issue to our engineering team.

    As a workaround, you should remove the explicit cast to 'unsigned char', or you add another explicit cast so that the result of the sum is calculated as an 'unsigned int'.
    dd = (unsigned char)(((unsigned int)(aa+bb))%255);

Reply
  • I think you have found a compiler issue. I was able to reproduce it. Do you have a valid license? If yes, it would be good if you would raise a support case so that we can notify you once this issue is fixed.

    The expression "(unsigned char)((aa+bb)%255)" is calculated only 8 bit wide because of the cast to 'unsigned char' (which is wrong). So in this case 0xab+0xcd is calculated to 0x78 instead of 0x0178. The modulo 255 then calculates 0x78 instead of 0x79. I have forwarded this issue to our engineering team.

    As a workaround, you should remove the explicit cast to 'unsigned char', or you add another explicit cast so that the result of the sum is calculated as an 'unsigned int'.
    dd = (unsigned char)(((unsigned int)(aa+bb))%255);

Children