Rounding down the given unsigned integer to nearest power of 2
or
Find the nearest power of 2 which is less than the given number
#include <stdio.h>unsigned int flp2(unsigned int x) ;
int main()
{
unsigned int x;
scanf("%u",&x);
printf("%u\n",flp2(x));
}
unsigned int flp2(unsigned int x)
{
unsigned int y;
y = 0x80000000;
while (y > x)
y = y >> 1;
return y;
}
OR
#include <stdio.h>
unsigned int flp2(unsigned int x) ;
int main()
{
unsigned int x;
scanf("%u",&x);
printf("%u\n",flp2(x));
}
unsigned int flp2(unsigned int x)
{
unsigned int y;
do {
y = x;
x = x & (x - 1);
}
while(x != 0);
return y;
}
OR
#include <stdio.h>
unsigned int flp2(unsigned int x) ;
int main()
{
unsigned int x;
scanf("%u",&x);
printf("%u\n",flp2(x));
}
unsigned int flp2(unsigned int x)
{
x = x | (x >> 1);
x = x | (x >> 2);
x = x | (x >> 4);
x = x | (x >> 8);
x = x | (x >>16);
return x - (x >> 1);
}
No comments:
Post a Comment