Re: portable way to get highest bit set?

Lew Pitcher <[email protected]> Thu, 12 Oct 2023 23:47:35 -0000 (UTC)
Newsgroups comp.lang.c,alt.comp.lang.c
Organization A noiseless patient Spider
Message-ID <[email protected]>
On Thu, 12 Oct 2023 23:35:08 +0000, Lew Pitcher wrote:

> On Wed, 11 Oct 2023 14:54:32 +0000, Lew Pitcher wrote:
> 
>> On Wed, 11 Oct 2023 01:56:49 -0500, candycanearter07 wrote:
>> 
>>> Hi,
>>> 
>>> What is the best/most portable way to get the highest bit set?
>>> 
>>> ie. 011010001 to  010000000
>> 
>> What have you tried?
>> 
>> I can think of one way, but it may not be the "best" or "most portable"
>> way of setting the highest bit of a value, and it /does/ have some
>> limitations. Show your work, and I might show mine.
> 
> #include <limits.h>
> unsigned long long int msb_mask(unsigned long long int valu)
> {
>   unsigned long long int mask;
> 
>   for (mask = ((ULLONG_MAX) ^ (ULLONG_MAX >> 1));
>        mask && !(mask&valu);
>        mask >>= 1) continue;
>   return mask&valu;
> }

Well, I'll be go to COBOL. A minor tweak just occurred to me.

unsigned long long int msb_mask(unsigned long long int valu)
{
  unsigned long long int mask;

  for (mask = ((ULLONG_MAX) ^ (ULLONG_MAX >> 1));
       mask && !(mask&valu);
       mask >>= 1) continue;
  return mask;	/* don't need to AND with valu now */
}



-- 
Lew Pitcher
"In Skills We Trust"