c++math

How to align a value to a given alignment


I have a value that I want to align to a given alignment, ie increase the value to the next multiple of the alignment if it is not already aligned.

What is a concise way to do this in C++?

eg

int x;
int alignment;
int y = ???; // align x to alignment

Solution

  • Lets say alignment is a

    ---(k-1)a-----------x--------------ka---------
             <----r----><-----(a-r)--->
    

    where k is an integer (so ka is a multiple of alignment)

    First find the remainder

    r = x%a

    then increment x to next multiple

    y = x + (a-r)

    But if r = 0, then y = x

    So finally

    r = x%a;
    y = r? x + (a - r) : x;