Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align a value to a given alignment

Tags:

c++

math

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
like image 830
ljbade Avatar asked Oct 04 '12 06:10

ljbade


People also ask

What is align in C++?

alignof and alignas The alignas type specifier is a portable, C++ standard way to specify custom alignment of variables and user defined types. The alignof operator is likewise a standard, portable way to obtain the alignment of a specified type or variable.

What is 64 bit alignment?

64-bit aligned is 8 bytes aligned). A memory access is said to be aligned when the data being accessed is n bytes long and the datum address is n-byte aligned. When a memory access is not aligned, it is said to be misaligned. Note that by definition byte memory accesses are always aligned.

What does 4 byte aligned mean?

A 1-byte variable (typically a char in C/C++) is always aligned. A 2-byte variable (typically a short in C/C++) in order to be aligned must lie at an address divisible by 2. A 4-byte variable (typically an int in C/C++) must lie at an address divisible by 4 and so on.


2 Answers

If the alignment is a power of 2, and the machine uses complement of 2 for negative numbers then:

mask = alignment - 1;
aligned_val = unaligned_val + (-unaligned_val & mask);
like image 81
Robert Andrzejuk Avatar answered Sep 29 '22 02:09

Robert Andrzejuk


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;
like image 38
Shashwat Avatar answered Sep 29 '22 03:09

Shashwat