c - Generic function for comparing two integers? -


is there standard c (linux) function, or code-efficient good-performing approach, comparing 2 integers of arbitrary size?

i'm looking parameters int intcmp(const void *a, const void *b, size_t size) works on integers a , b practical size size. (memcmp() work (i think) if architecture big endian.)

the implementation tend use goes (with improvements efficient integer compare function) it's not generic , has enough of code overhead think twice before slotting 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; } 

static inline functions have advantage of arguments being evaluated once (this hard/impossible macros) . allow function calls int diff = cmp_all (p++, q++, sizeof *p); :

#include <stdlib.h> #include <stdint.h>  static inline int cmp1(const int8_t *one, const int8_t *two) { if (*one < *two) return -1; else if (*one > *two) return 1; else return 0; }  static inline int cmp2(const int16_t *one, const int16_t *two) { if (*one < *two) return -1; else if (*one > *two) return 1; else return 0; }  static inline int cmp4(const int32_t *one, const int32_t *two) { if (*one < *two) return -1; else if (*one > *two) return 1; else return 0; }  static inline int cmp8(const int64_t *one, const int64_t *two) { if (*one < *two) return -1; else if (*one > *two) return 1; else return 0; }  int cmp_all(const void *one, const void *two, size_t size) { switch(size) { case 1: return cmp1(one, two); case 2: return cmp2(one, two); case 4: return cmp4(one, two); case 8: return cmp8(one, two); default: return 0; /* teach them ... */         } } 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -