2

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.

  • Are you looking for binary and? (`22 & 16 == 16`) – cbr Aug 30 '17 at 14:32
  • So you want to keep the highest bit that is 1 and set all the other ones to zero? Examples: 1010 -> 1000, 10100111 -> 100000000, 111 -> 100 etc. There is no such inbuilt function, but you can easily write one yourself (estimated 4-5 lines). – Jabberwocky Aug 30 '17 at 14:34
  • @cubrr If I already have value 16 then what is the use of doing AND here. example if the input is 86 then its 2nd operand I need to calculate and that is my aim. – user5708039 Aug 30 '17 at 14:35
  • Maybe a duplicate of https://stackoverflow.com/questions/53161/find-the-highest-order-bit-in-c – Jabberwocky Aug 30 '17 at 14:37
  • @MichaelWalz, yeah, some answers match perfectly this question (even if the original wording of the question is different) – Jean-François Fabre Aug 30 '17 at 15:19
  • Possible duplicate of [Find the highest order bit in C](https://stackoverflow.com/questions/53161/find-the-highest-order-bit-in-c) – Jean-François Fabre Aug 30 '17 at 15:20

2 Answers2

1

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)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

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);
}
Andriy Berestovskyy
  • 8,059
  • 3
  • 17
  • 33
  • 1
    This doesn't work if the top bit of the input is set, e.g. `floor_align32pow2(0x80000000)` will return 0 instead of 0x80000000. You can fix it with `return (x >> 1) + (x & 1);`. – Ian Abbott Aug 30 '17 at 15:54