Path: csiph.com!news.mixmin.net!eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail
From: Tim Rentsch
Newsgroups: comp.lang.c
Subject: Re: portable way to get highest bit set?
Date: Wed, 11 Oct 2023 10:17:17 -0700
Organization: A noiseless patient Spider
Lines: 35
Message-ID: <86mswpaxk2.fsf@linuxsc.com>
References: <20231011102714.44a870af4dfe68f756974953@g{oogle}mail.com>
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Injection-Info: dont-email.me; posting-host="c9974d524a342450c72757464b9d47a6"; logging-data="2054933"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19pFEs/MpMIrUDUKjPgvT1KpvBcRDzi72M="
User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux)
Cancel-Lock: sha1:E+LqWDmpG+ZoIUJx8hZV8q+EPIc= sha1:Msmg1AVUwoh/Mcfn5mHFd1HDFTQ=
Xref: csiph.com comp.lang.c:228443
Ian C writes:
> 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.
Wouldn't you first write a test function to be sure the
value returned is correct? ;)
I found it harder to write a correct test function than
to write a function that just returns a correct value.
Interesting, eh?