Thursday, March 1, 2012

Next Multiple of 8

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

Code: 

#include <stdio.h>
#include <stdlib.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));
    system("pause");
    return 0;
}

No comments:

Post a Comment