[Coco] Drivewire mixed results...
Chuck Youse
cyouse at serialtechnologies.com
Thu Sep 25 09:27:05 EDT 2008
On Thu, 2008-09-25 at 07:56 -0500, Boisy Pitre wrote:
> On Sep 25, 2008, at 7:52 AM, Chuck Youse wrote:
>
> >
> >>>
> >>> int calChecksum(char *ptr, int count)
> >>> {
> >>> short Checksum = 0;
> >>> while(--count)
> >>> {
> >>> Checksum += *(ptr++);
> >>> }
> >>> return (Checksum);
> >>> }
> I don't see right off-hand how that might be, but I'm open to
> suggestions. Feel free to provide an improved function and I'll
> certainly incorporate it into the next rev of the specification
> document.
You need to be explicit about the signedness of 'char *ptr'. Since the
early days of C this has been an implementation-specific detail - ANSI
both solved and compounded the problem by adding 'signed char' and
'unsigned char', which are distinct from 'char'. (This is of course not
orthogonal with respect to integers, which are by default signed.)
In any case, for usual checksum computations this wouldn't matter
because two's complement and modulo arithmetic is nifty. Unfortunately,
you're computing a 16-bit checksum for 8-bit data, which means that
whether or not the addend at *ptr is sign-extended is significant.
And no, I'm not just being pedantic; this actually matters. Even gcc on
different architectures will implement the rules differently depending
upon what is most natural for that architecture, or [where applicable]
how the native compiler behaves, or what compile-time options are given
it..
Also, (and this IS me being pedantic), declaring Checksum as 'short' is
superfluous. Declaring it as an 'int' would have the same effect, and
would avoid any penalties that are imposed by dealing with something
smaller than the natural word-size (which can be significant, especially
in loops). Hardly matters on today's machines for something like
Drivewire, but I only SOMETIMES use that as an excuse to get sloppy :)
C.
More information about the Coco
mailing list