Reputation: 45
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
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
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