Is there a fairly standard C (Linux) function, or a code-efficient but good-performing approach, for comparing two integers of an arbitrary size?
I'm looking for something with the parameters int intcmp(const void *a, const void *b, size_t size)
that works on integers a
and b
for any practical size size
. (memcmp()
would work (I think) if the architecture was big endian.)
The implementation I tend to use goes like this (with improvements from Efficient integer compare function) but it's not completely generic and has enough of a code overhead that I generally think twice before slotting it in.
int intcmp(const void *a, const void *b, size_t size) {
#define CASE_SIZE_RETURN_A_B_CMP(_t) \
case sizeof(_t): \
return ((*(_t *)(a) > *(_t *)(b)) - (*(_t *)(a) < *(_t *)(b)))
switch (size) {
CASE_SIZE_RETURN_A_B_CMP(char);
CASE_SIZE_RETURN_A_B_CMP(short);
CASE_SIZE_RETURN_A_B_CMP(int);
CASE_SIZE_RETURN_A_B_CMP(long long);
}
#undef CASE_SIZE_RETURN_A_B_CMP
assert(0);
return 0;
}