CCS - Conversions between different types
Barry King email (remove spam text)
This is really a C question, but its specific to this implementation.
> long a;
> long b;
> signed long s;
in CCS "long" is an unsigned long, CONTRARY TO THE C STANDARD,
where by default, integers are signed unless declared otherwise.
"unsigned long" is always the unsigned type.
> b = 1000;
> a = 500;
> s = b - a;
> I assume S is supposed to be a negative number now (- 500 decimal)
Uh... 1000 - 500 is 500.
I think you mean a - b, which is more interesting.
Since a and b are unsigned, the expression a - b is also unsigned,
and since this is an "underflow", you get the result that:
500 - 1000 = 65036
because what the machine did was:
01F4 - 03E8 = FE0C (plus a borrow out, which is discarded)
But, since CCS uses two's complement format for signed integers, the
bit pattern in the result is the same for signed or unsigned. (I
suspect the code is the same, too.)
The assignment then makes an implicit cast of the unsigned result
to a signed number. I don't know for sure how CCS interprets that
cast. A test program is the best way to find out; on most
implementations, the result should be the same bit pattern, so the
result should be -500.
I will not repeat my past rant about how I no longer trust this
compiler. Your milage may vary; again, a quick test program will
> if (S < 0)
> Will it then execute subroutine1 Like I think it should?
I predict it will.
> then if I do:
> b = s; // Don't try this at home - warning type conversion
Again, this is a cast, this time from signed to unsigned. The
interpretation is likely a direct copy, so the bit pattern is
preserved. So now if b = s = a-b, b is 65036.
> It should make a mess out of B, it should be 65536 - 500 = 65036 decimal,
Yes. Its not a mess exactly- its predictable, but it might not be
what you meant. That's what the warning means.
So... in practice, make the casts explicit, so that your intent is
clear. If you WANT to assign a signed to and unsigned, do:
b = (unsigned)s;
Which makes the same code, but makes it clear you did the
conversion on purpose and are prepared to take the consequences :)
The compiler shouldn't warn you anymore.
Hope this helps,
NRG Systems "Measuring the Wind's Energy"
In reply to: <email@example.com>
See also: www.piclist.com/techref/index.htm?key=ccs+conversions
You must be a member of the
piclist mailing list
(not only a www.piclist.com member) to post to the