Friday, November 2, 2007

Next multiple of 8

Given a number(n), the task is to find out the number just grater than n and multiple of 8.

This could be achieved by:
n = (n +7) &~7.

This concept can be extended to multiple of 2^x. (2^x is 2 raised to the power x)
n = (n+ (2^x)-1)&~((2^x) - 1)

Next multiple of 8 is of practical use as this could be used in memory allocation algorithms to make the start address multiple of 8 so as to avoid misaligned memory access.