In article <45b1ab9a$0$58034$(E-Mail Removed) s.com>,

Thad Smith <(E-Mail Removed)> wrote:

> Francois Grieu wrote:

> > This macro returns 1 if the low 8 bits of x form a valid BCD value,

> > and 0 otherwise.

> >

> > #define VALIDBCD(x) (((x)&0x0F)<0x0A && ((x)&0xF0)<0xA0)

> >

> > How do you rewrite it so that it evaluates its argument only once,

> > requires no temp variable or table, and is fully C99 compliant?

>

> #define VALIDBCD(x) !((((x)&0xee)+0x66)&0x110)
Yes, that's the best I could find in term of number of constants and

operators.

If the code is to run on an 8-bit machine, this likely is more efficient:

#define VALIDBCD(x) !((((x)>>1&0x77)+0x33)&0x8

Rather amazingly, even when sizeof(x) is 2, my usual embedded C

compiler (Metrowerks) needs no explicit cast to unsigned char

to make this generate a perfect stream of single-byte arithmetic/logic

operations.

Francois Grieu