c - 比较两个整数的通用函数?

标签 c

是否有相当标准的 C (Linux) 函数或代码高效但性能良好的方法来比较任意大小的两个整数?

我正在寻找具有参数 int intcmp(const void *a, const void *b, size_t size) 的东西,它适用于整数 ab 适用于任何实际尺寸 size。 (memcmp() 可以工作(我认为)如果架构是 big endian。)

我倾向于使用的实现是这样的(改进了 Efficient integer compare function )但它不是完全通用的并且有足够的代码开销,我通常在插入它之前三思而后行。

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;
}

最佳答案

静态内联函数的优点是参数只被评估一次(这对于宏来说很难/不可能)。这将允许像 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; /* that will teach them ... */
        }
}

关于c - 比较两个整数的通用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16515475/

相关文章:

c - 链接 C 中的另一个结构

c - 在函数 C 中传递并修改 char array[][]

c++ - 处理数组

c - 替换#defines常量

c - 在 C 中用 select() 读取然后写入?

c - 字节交换/反转字符数组

c - 如何释放结构体c中的双指针?

c - 在 C 中的 main() 之前和之后定义一个函数?

检查输入的值是否包含数字

C 函数意外改变值