Question: Given any number say 12, find the next multiple of 8 eg 16 using bit-wise manipulations.?
Solution: #include
int nextmul8(int n)
{
if(n & 7) //if it is not multiple of 8
{
n &= ~7; //turn off last 3 bits
//Add 8 to n
int m = 8;
while(n & m)
{
n &= ~m;
m <<= 1;
}
n |= m;
}
return n;
}
int main()
{
int n;
scanf("%d", &n);
printf("%d\n", nextmul8(n));
}