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

size = (((aa+1)*(bb+1))<<1) ??

hi
I have write a smaple code like this

uint size =0;
uchar aa = 0x15;
uchar bb = 0x11;

size = (((aa+1)*(bb+1))<<1);

why size is 0x18 not 0x318??
How to get correct answer??

thanks a lot

Parents Reply Children
  • The uint is define as unsigned int

    No ,I didn't set "Enable ansi integer promotion ruls", Do I need to set this ??

    Thanks for your kindly hlep^^"""

  • ",I didn't set 'Enable ansi integer promotion ruls', Do I need to set this ??"

    Well, it looks like it's doing the calculation in a char size, doesn't it?

    ANSI would "promote" everything to ints first, then do the calculation in int size - but this is not necessarily a good thing on an 8-bit processor, which is why Keil gives you the option to disable it.

    You could try casting to int?

  • Thanks again^^

    I try to casting it like this

    size = (((uint)(aa+1)*((uint)(bb+1)))<<1);

    it seem look like work well

  • Yes. The casts force the calculation to be done at int width (16 bits for Keil C51). The compiler option for automatic integer promotion would have done the same thing automatically.

    The ANSI C specification has rules for automatically "promoting" 8-bit values in this sort of calculation to integers. On an 8-bit processor, doing 16-bit math is less efficient and often unnecessary. So, C51 does not follow the integer promotion rules unless you ask it to do so. You can trade off slightly non-standard language behavior for higher efficiency. Or, you can insist on standard behavior if that is more important to you.