Velocity Reviews > bitwise operator !!

# bitwise operator !!

Tim Rentsch
Guest
Posts: n/a

 01-08-2009
http://www.velocityreviews.com/forums/(E-Mail Removed) (blargg) writes:

> Tim Rentsch wrote:
> > (E-Mail Removed) (blargg) writes:

> [...]
> > > What's wrong with the following (posted to this thread a while back)
> > >
> > > (x < 0) ? -(int) (-(unsigned) x >> 5) : x >> 5
> > >
> > > ? It should be the same efficiency (negate, shift, negate, as opposed to
> > > complement, shift, complement yours does), and completely portable without
> > > even touching signed value representation issues.

> >
> > The drawback is, it can yield a wrong result on implementations where
> > UINT_MAX == INT_MAX, which is allowed by the Standard. So it isn't
> > quite as portable as it might appear.

>
> So if INT_MAX = UINT_MAX = 0x7FFF, INT_MIN = -0x8000 and x = INT_MIN, then
> (unsigned) x = 0. Oh well. But are such implementations allowed? (as in,
> care to reference/quote the sections of the standard?)

Do you have a copy of the Standard? If you don't, try googling
for n1256, which should get you to the latest revision of C99
standard. I really recommend that you get one.

The relevant citation is 6.2.6.2 p 2

For signed integer types, the bits of the object representation shall
be divided into three groups: value bits, padding bits, and the sign
bit. There need not be any padding bits; there shall be exactly one
sign bit. Each bit that is a value bit shall have the same value as
the same bit in the object representation of the corresponding
unsigned type (if there are M value bits in the signed type and N in
the unsigned type, then M <= N). If the sign bit is zero, it shall
not affect the resulting value. If the sign bit is one, the value
shall be modified in one of the following ways: [...goes on...]

If M == N then the unsigned type has the same number of value bits
as the signed type, e.g., UINT_MAX == INT_MAX.