Date: Thu, 21 Mar 2013 18:42:16 +0000 From: Taylor R Campbell <[email protected]>
/* typeof-free roundup2/rounddown2 */ #define roundup2(x, m) (((x) + ((m) - 1)) & ~((m) - 1 + ((x) - (x)))) #define rounddown2(x,m) ((x) & ~((m) - 1 + ((x) - (x)))) /* multiple-evaluation-free roundup2/rounddown2 */ #define roundup2(x, m) ((((x) - 1) | ((m) - 1)) + 1) #define rounddown2(x,m) ((x) &~ ((typeof(x))((m) - 1))) Another possibility for rounddown2 which avoids multiple evaluation and typeof, but requires uintmax_t and wants a little help from the compiler, is #define rounddown2(x,m) ((x) & ~(uintmax_t)((m) - 1)) or #define rounddown2(x,m) ((x) & -(uintmax_t)(m)) to make it a little terser.
