Yahoo Groups archive

Lpc2000

Index last updated: 2026-04-28 23:31 UTC

Message

Re: [lpc2000] Re: For C novices

2006-03-31 by Robert Adsett

Quoting Clyde Stubbs <clyde@...>:

> On Fri, Mar 31, 2006 at 02:20:12AM -0000, garycordelli wrote:
>> Just a postscript: this is not an academic notion to which I allude,
>> but a common error in just the kind of code I am paid to fix every day.
>>
>> The circumstances tend to be communications code, where the programmer
>> has created a generic n-byte buffer:
>
<snip>
> The bottom line - if you want to *portably* encode/decode bytestreams of this
> nature you have to do it one byte at a time. There is no other way to ensure
> that the same code will work across different architectures.

Amen.  Do it right, save yourself future headaches.  Separate the 
communications
format from the internal structure. Even if they happen to match.

> Wanna encode a
> 16 bit value as two sequential bytes? Do it like this:
>
> 	*cp++ = (val & 0xFF);
> 	*cp++ = (val >> 8) & 0xFF;
>
> The masking is redundant, but makes it clear what you're doing, and will be
> optimized away by any decent compiler.

The harder part is going the other way and making sure things get sign 
extended
properly, especially if communication size and internal storage size don't
match.

As a for instance I've seen CAN protocols that use a 10bit signed int 'across
the wire'

> Now if you happen to have code that someone naively wrote that only works
> on one particular architecture - don't expect a compiler to save you. Just
> bite the bullet, rewrite the code properly, and learn from the experience.
> It will save you a LOT of time in the long run.

And get yourself a good lint, theres a good chance there are more 
gotchas hidden
in the code.

Robert

Attachments

Move to quarantaine

This moves the raw source file on disk only. The archive index is not changed automatically, so you still need to run a manual refresh afterward.