gpt4 book ai didi

c - 如何将复合文字用于 `fprintf()` 具有任意基数的多种格式化数字?

转载 作者:太空狗 更新时间:2023-10-29 17:17:11 25 4
gpt4 key购买 nike

我想将多个数字转换成某种表示形式,然后使用 *printf() 说明符的标志、宽度和精度。首选是避免全局或 static 缓冲区。关键问题似乎是如何为每个转换后的数字提供 char[]

fprintf(ostream, "some_format", foo(int_a, base_x), foo(int_b, base_y), ...);

How to use C11 compound literals to solve this?
How to use C99 (or later) compound literals to solve this?

最佳答案

C99 C11 引入了复合文字,它不仅允许复杂的初始化结构,还允许“内联”变量。

代码可以调用一个转换函数并传入一个新的缓冲区 (char [UTOA_BASE_N]){0} 每个函数调用允许函数返回相同的缓冲区,现在根据需要编写 < em>仍在其生命周期内。然后使用 "%s" 说明符可用的各种标志、宽度和精度打印返回的字符串。

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

// Maximum buffer size needed
#define UTOA_BASE_N (sizeof(unsigned)*CHAR_BIT + 1)

char *utoa_base(char *s, unsigned x, unsigned base) {
s += UTOA_BASE_N - 1;
*s = '\0';
if (base >= 2 && base <= 36) {
do {
*(--s) = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[x % base];
x /= base;
} while (x);
}
return s;
}

#define TO_BASE(x,b) utoa_base((char [UTOA_BASE_N]){0} , (x), (b))

void test(unsigned x) {
printf("base10:%10u base2:%5s base36:%s ", x, TO_BASE(x, 2), TO_BASE(x, 36));
printf("%lu\n", strtoul(TO_BASE(x, 36), NULL, 36));
}

int main(void) {
test(0);
test(25);
test(UINT_MAX);
}

输出

base10:         0 base2:    0  base36:0 0
base10: 25 base2:11001 base36:P 25
base10:4294967295 base2:11111111111111111111111111111111 base36:1Z141Z3 4294967295

引用:Is there a printf converter to print in binary format? 有很多答案,但没有一个允许上面的简单内存管理(没有 static)访问 fprintf() 标志宽度,精度并使用数字的全范围。

这是一个 Answer your own question 答案。

关于c - 如何将复合文字用于 `fprintf()` 具有任意基数的多种格式化数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34292060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com