C 当 printf 将 long long 转换为 %o (unsigned int) 时发生了什么

C what is happening when printf convers long long to %o (unsigned int)

我正在尝试复制 printf,因为不允许我在作业中使用真实的,而且我不明白当我传递一个太大的值时会发生什么:

unsigned int n = 4294967286;
printf("%o", n); #=> 37777777766
my_printf("%o", n); #=> 4256507006;

我得到的值是这样的:

a = (unsigned int)(va_arg(f->l, unsigned int));

然后我使用我的 ui_to_s 来获取相应的字符串:

char *ui_to_s_base(unsigned long long n, int base, const char *base_set)
{
    const char  *defaut_base = "0123456789abcdef";
    char        *res;
    char        *tmp;
    unsigned long long   i;

    tmp = str_new_size(256);
    i = 0;
    tmp[i++] = base_set ? base_set[(n % base)] : defaut_base[(n % base)];
    while ((n /= 10) > 0)
        tmp[i++] = base_set ? base_set[(n % base)] : defaut_base[(n % base)];
    tmp[i] = '[=12=]';
    res = str_reverse(tmp);
    free(tmp);
    return (res);
}

我是不是做错了什么?

while ((n /= 10) > 0)

你应该除以 base。只要你要求它以十进制打印,10 就会像一个魅力一样工作。

我想这个故事的寓意是,如果您在某些包含非平凡常量的代码中有错误,那可能是开始调查的好地方。