Re: portable way to get highest bit set?

Ian C <[email protected]> Wed, 11 Oct 2023 18:03:38 +0100
Newsgroups comp.lang.c,alt.comp.lang.c
Organization A noiseless patient Spider
Message-ID <[email protected]>
On 11/10/2023 17:19, candycanearter07 wrote:
> On 10/11/23 02:27, Anton Shepelev wrote:
>> candycanearter07:
>>
>>> What is the best/most portable way to get the highest bit
>>> set?
>>>
>>> ie. 011010001
>>> to  010000000
>>
>> What is your best attempt, even if unsuccessful?
>>
> 
> int out;
> for(out = 0x100000000; out; out >> 1)
>      if(out & input) break;
> 
> I'm trying to find something size independent, though.
> Or at least able to be swapped out with a #define

If you want the highest bit, 0x800000000 may be a better start :-)

If it was me I'd do it in reverse.  Assuming it's unsigned, shift your 
input to the right until it hits zero, counting the number of shifts 
which will be your bit number.  Assuming my head is currently working.


Ian C