Monday, July 31, 2006

Multiple of 8

using bit manipulation, find next multiple of 8 for a given number

int nextMultipleOfEight(int num)
{
i = i rightShift 3;
i++;
i=i leftShift 3;
printf("%d\n",i);
}

2 comments:

  1. a simple one i think is like this

    nextmul = num + (num &7)

    ReplyDelete
  2. sorry a modification to my earlier answer


    nextmul8 = 8 +
    (num - (num & 7))

    this can be genralised for any power of 2 number

    x is power of 2
    nextmulofx
    = x+ (numinput - (numinput & (x-1)))

    ReplyDelete