When I browsing c++ header files of opencv, It happened to see the construct (ptr + n-1) & -n
in alignPtr
function. The complete function as follows
/*!
Aligns pointer by the certain number of bytes
This small inline function aligns the pointer by the certain number of bytes by shifting
it forward by 0 or a positive offset.
*/
template<typename _Tp> static inline _Tp* alignPtr(_Tp* ptr, int n=(int)sizeof(_Tp))
{
return (_Tp*)(((size_t)ptr + n-1) & -n);
}
Can you explain how it works?