将 unsigned long 传递给使用 long 的函数是否不安全?

Is it unsafe to pass an unsigned long to a function which uses a long?

前言: 我不允许使用 C 库中的任何函数

我有这个功能:

char *to_base(long nbr, char *base)
{
    static char buffer[50];
    char    *ptr;
    int     base_len;

    ptr = &buffer[49];
    *ptr = 0;
    base_len = ft_strlen(base);
    while (nbr != 0)
    {
        *--ptr = base[nbr % base_len];
        nbr /= base_len;
    }
    return (ptr);
}

正如我们所见,这需要很长时间。在我的程序中,我有一个 unsigned long,我必须将其转换成它的十六进制值。在此函数中传递 unsigned long 是否不安全?如果是,我怎样才能让它工作?

编辑: 以下是我目前的使用方式:

unsigned long    val;
char            *hexa;

val = (unsigned long)va_arg(*list, void *);
hexa = to_base(val, "0123456789abcdef");

Is it unsafe to pass the unsigned long at this function ?

它是“安全的”,因为在程序中不会格式化您的硬盘或启动另一个世界war。

传递的函数参数转换为参数类型。无符号值将转换为有符号值。今天所有的架构都使用二进制补码,很容易预测结果。您的编译器应该记录行为,例如。在 gcc implementation defined beahvior:

The result of, or the signal raised by, converting an integer to a signed integer type when the value cannot be represented in an object of that type (C90 6.2.1.2, C99 and C11 6.3.1.3).

For conversion to a type of width N, the value is reduced modulo 2^N to be within range of the type; no signal is raised.

"reduced modulo 2^N" - 基本上减去 2^N 直到值在范围内。因此,如果您有 32 位 longs 并且有 (long)(unsigned long)4294967196ul,那么您从该值中减去 2^32,它等于 (long)-100.

If yes how can I make it work ?

正确处理负数。

并为无符号数和有符号数编写一个单独的函数。

另外 (unsigned long)va_arg(*list, void *); 正在将 void* 指针值转换为 unsigned long (?)。您很可能希望 va_arg(list, unsigned long) - 从参数中获取 unsigned long