Re: Inconsistent behaviour for (1 << 32)
"Daniel Kraft" <d@domob.eu> a écrit dans le message de news:
ffcjh5$8s6$1@newsreader2.utanet.at...
> Daniel Kraft wrote:
>> >> 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).
>
> I think I found a solution:
>
> instead of (1 << getBits()) which might result in this undefined behaviour
> I do (2 << (getBits()-1)) (getBits() is never 0). This should be
> well-defined, right?
So you came up with one of my proposed solutions on your own ;-)
This one is well defined only upto 31, because 2 is an int, and behaviour on
overflow is implementation defined. Use (2U << (getBits()-1)) to fix this,
but look at my last proposal elsethread that requires fewer operations to
compute the mask itself.
--
Chqrlie.
|