How to align a value with a given alignment

I have a value that I want to align with the given alignment, i.e. increase the value until the next multiple alignment, if it is not already aligned.

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

eg,

int x; int alignment; int y = ???; // align x to alignment 
+6
source share
1 answer

Assume alignment a

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

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

First find the rest

r = x%a

then increment x to the next edge

y = x + (ar)

But if r = 0, then y = x

So finally

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

Source: https://habr.com/ru/post/926916/


All Articles