Shaun Jackman <sjackman@nospam.vortek.com> wrote:
Here’s a nice light question. What’s the most portable/elegant way of
representing the data word consisting of all set bits?
A signed integer with all bits set to one, including the sign bit,
could be a trap representation on a one’s-complement machine. If you
don’t care about the sign bit, I think INT_MAX should do it, at least
according to my reading of C99. But it doesn’t feel right, does it?..
(I don’t have a copy of C89, but I think it gave implementations more
freedom in this area; I wouldn’t be suprised if it turned out that C89
didn’t guarantee that INT_MAX has all the value bits set. Personally,
I’d avoid assuming that it does for another ten years or so…)
If you need an unsigned integer, then UINT_MAX, (unsigned)-1, -0u and
~0u are all guaranteed to work and produce the same result. But you
can’t safely convert it back to int.
// example usage: clear all the bits of foo
atomic_clr( &foo, ALL_ONES);
Some thoughts…
#define ALL_ONES -1
works on twos complement machines, but not ones complement nor
sign-magnitude.
Right. But if works if you convert it to an unsigned type.
#define ALL_ONES UINT_MAX
works on all machines I think. Any example of an architecture where it
doesn’t?
It’s guaranteed to work unless you try to convert it to a signed type
that can’t preserve the value.
#define ALL_ONES (~0)
pretty much the definition of all-ones. I think this is best. Any reason
why not?
It’s undefined behavior on a one’s-complement implementation that
doesn’t support negative zeros.
–
Wojtek Lerch QNX Software Systems Ltd.