Re: portable way to get highest bit set?

Ben Bacarisse <[email protected]> Wed, 11 Oct 2023 23:58:10 +0100
Newsgroups comp.lang.c,alt.comp.lang.c
Organization A noiseless patient Spider
Message-ID <[email protected]>
jak <[email protected]> writes:

> candycanearter07 ha scritto:
>> Hi,
>> What is the best/most portable way to get the highest bit set?
>> ie. 011010001
>> to  010000000
>
> Hi,
> I don't think it's the best but the most portable could be the
> mathematical approach:
>
> #include <stdio.h>
> #include <math.h>
>
> int main()
> {
>     unsigned long val = 3000, ret;

Test case: val = 0xFFFFFFFFFFFFFFFF

>     ret = (unsigned long)pow(2., (double)(unsigned long)(log((double)val) /
>    log(2.)));
>
>     printf("%lu -> %lu", val, ret);
>
>     return 0;
> }

-- 
Ben.