Velocity Reviews > C++ > testing if just one bit is set...

# testing if just one bit is set...

James Kanze
Guest
Posts: n/a

 11-15-2008
On Nov 15, 2:56*pm, (E-Mail Removed) (blargg) wrote:
> James Kanze wrote:
> > On Nov 14, 6:48=A0pm, "Andrew Koenig" <(E-Mail Removed)> wrote:
> > > "Victor Bazarov" <(E-Mail Removed)> wrote in message
> > >news:gevfrd\$q4n\$(E-Mail Removed)...
> > > >> If n has an unsigned type (i.e. unsigned int or unsigned
> > > >> long), then (n&-n) is equal to n unless n has more than one
> > > >> bit set. *So the expression you're looking for is n!=(n&-n)

> > > > Wow... Does it work for any representation (two's
> > > > complement, one's complement, signed magnitude)?

> > > Just 2's complement -- but that's what everyone uses these
> > > days anyway.

> > Andy, what's up? *In your posting, you specifically said "If n
> > has an unsigned type". *And you know very well that the standard
> > defines - for unsigned types exactly.

> Presumably "works for any representation" meant that things
> OTHER than unsigned were being considered, since unsigned
> types use two's complement and nothing else.

Given that two's complement specifies how to represent negative
values, given a base 2 representation for positive values, I
don't see how one can say that unsigned types use two's
complement.

> And it's true, said expression does NOT work for
> representations other than two's complement. Since almost
> everything uses two's complement these days, said expression
> will thus work even for signed types on almost everything.

For some sufficiently weak definition of "almost". Whether you
like it or not, machines are still being sold that don't use
two's complement, and at least one of them supports C++. If the
only machines you have to worry about are PC's, fine. You can
ignore portability issues. Otherwise...

--
James Kanze (GABI Software) email:(E-Mail Removed)
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34