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=0x79dd = (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.
why does nobody reply my question ?
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);
Thank you for your reply. I have the license of C51 7.10 only. I just want to confirm whether it's a bug and how can I pay attention to code.
Thanks again.
Thanks for reporting this bug.
It would be very helpful for us to track this issue if you could create a Support Ticket according to:
https://www2.keil.com/support/silver?P=&V=&S=
Just for your information: This issue is now solved with C51 compiler version 9.60.2. This version (or newer) will be part of PK51 version 9.61 (or later), but the date of this next PK51 release is not scheduled yet. If the support period of your license is not expired and you want to receive C51 version 9.60.2, please raise a support case and refer to this forum post.