To find the next multiple of 8 of a number using only bit-wise manipulations

#include <stdio.h>

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));
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s