Re: code questions.

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi,

Thanks so much for your quick reply. This code is simliar to code in a
third party source code that I have to fix and they do this all over
the place. The question is w/o touching their code is there a way I
can fix this? I tried explicitly casting the 1 to an unsigned short
but it doesn't seem to work like this:

a = (a + (unsigned short) 1) % b.

Thanks for your help.

Scott

On Mon, Jun 2, 2008 at 6:59 PM, me22 <me22.ca@xxxxxxxxx> wrote:
> On Mon, Jun 2, 2008 at 9:48 PM, Scott Phuong <mycleanjunk@xxxxxxxxx> wrote:
>>
>>        unsigned short a;
>>        unsigned short b;
>>
>>        a = 0xFFFF;
>>        b = 0x3FC;
>>
>>        a = (a + 1) % b;
>>        printf ("A is 0x%x\n", a);
>>        // I expect the answer to be 0 and it is not! It is 0x100. Why is this?
>>
>
> I bet if you did
>
>    ++a; a %= b;
>
> you'd get 1.
>
> I don't know the exact rules, but 1 is an int, so a+1 will give you
> (int)a + 1, which will be 0x10000, which when modded by (int)b will
> not be 0.
>
> I'd have to read up on integral promotion to be sure, but I think the
> only way is to add an explicit cast.
>
>    a = (unsigned short)(a+1) % b;
>
> (If you want to keep it one expression, and of that form.  ++a, a %=b;
> is possible, as mentioned, and a = ( (a+1) & 0xFFFFu ) % b would also
> work.)
>
> HTH,
> ~ Scott
>

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux