[ create a new paste ] login | about

Link: http://codepad.org/l6FylgFH    [ raw code | output | fork ]

C, pasted on Sep 2:
#include <stdio.h>

// rounds n (upwards) to a multiple of f while preserving the sign-bit of n

// The above comment is confusing. Is "upwards" towards 0? If so, the comment
// needs to be changed.
// HOWEVER, I don't think this is what the function is supposed to do!
//
static inline int round_multiple_nosign(int n, int f)
{
	int nn, ns;
	nn = (n >= 0) ? n : -n;
	ns = (n >= 0) ? 1 : -1;
	if (nn % f == 0)
		return n; // n == nn * ns
	else
		return ns * (n + f - (n % f));	// This should be ns * (nn + f - (nn % f));
}

// My version
// afz: away from zero
static inline int round_multiple_afz(int n, unsigned f)
{
	int sign = n < 0 ? -1 : 1;
	n *= sign;
	return sign * (n + f - n % f);
}

int main(void)
{
	printf("%d\n", round_multiple_nosign(-30, 16));
	printf("%d\n", round_multiple_afz(-30, 16));
	return 0;
}


Output:
1
2
0
-32


Create a new paste based on this one


Comments: