user5708039
user5708039

Reputation: 45

Toggle high bit to 1 and rest bits to 0 [example: 10110 to 10000]

I need to find out the mask value with respect to the number provided by the user.

For example. If user provides input as

22 (in binary 10110)

and then I need to find the mask value by changing the high bit of the input as 1 and rest to 0. So in this case it should be:

16 (in binary 10000)

Is there any inbuilt method in c language to do so.

Upvotes: 2

Views: 121

Answers (2)

Andriy Berestovskyy
Andriy Berestovskyy

Reputation: 8544

Basically, you need to floor align to the nearest power of two number. I am not sure there is a standard function for that, but try the following:

static inline uint32_t
floor_align32pow2(uint32_t x)
{
        x |= x >> 1;
        x |= x >> 2;
        x |= x >> 4;
        x |= x >> 8;
        x |= x >> 16;

        return (x >> 1) + (x & 1);
}

Upvotes: 0

Jean-François Fabre
Jean-François Fabre

Reputation: 140226

you could compute the position of the highest bit

Once you have it, just shift left to get the proper mask value:

   unsigned int x = 22;
   int result = 0;

   if (x != 0)
   {
     unsigned int y = x;
     int bit_pos=-1;
     while (y != 0)
     {
       y >>= 1;
       bit_pos++;
     }
     result = 1<<bit_pos;
   }

this sets result to 16

(there's a particular case if entered value is 0)

Upvotes: 1

Related Questions