Afficher un message
Vieux 20/10/2007, 11h02   #5
Charlie Gordon
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Inconsistent behaviour for (1 << 32)

"Daniel Kraft" <d@domob.eu> a écrit dans le message de news:
ffchgo$4gh$1@newsreader2.utanet.at...
> >> I did encounter a strange problem in my C program, and traced it down;
> >> it looks like I get different results for bit left shifts when the bit
> >> count is a constant or a funtion-return value.
> >>
> >> When doing (1 << 32) for a 32-bit-unsigned I expect to get 0;

> >
> > The behaviour is undefined if the number of bits by which you are

> shifting is >= the number of bits in the object.
>
> Ok, thank you!
>
> What I'm trying to do is this: I've got some unsigned type, and a
> function which returns a number of bits <= the number of usable bits of
> this type.
>
> I need to calculate (1 << getBits())-1, i.e., set the lower getBits() bits
> to one (which might be all ones if it is equal to the type's width, but it
> also might be only some less-significant-bits ones).
>
> Is there some other clever way to do this?


Use an array of unsigned ints with 33 elements.

unsigned int mask = mask_array[getBits()];

Or use a test:

unsigned n = getBits();
unsigned mask = (n < sizeof(unsigned) * CHAR_BIT) ? (1U << n) - 1 : -1U;

Ultimately, if you know that getBits() > 0 and no greater than the width of
the unsigned type, use this expression:

unsigned mask = ((1U << (getBits() - 1)) << 1) - 1;

or even:

unsigned mask = ~(-2U << (getBits() - 1));

or optimally:

unsigned mask = -1U >> (sizeof(unsigned) * CHAR_BIT - getBits());

--
Chqrlie.


  Réponse avec citation
 
Page generated in 0,04853 seconds with 9 queries