C99 C11 推出复合文字它不仅允许复杂的初始化结构,还允许“内联”变量。
代码可以调用转换函数并传入新的缓冲区(char [UTOA_BASE_N]){0}
每个函数调用允许函数返回相同的缓冲区,现在根据需要编写仍在其生命周期内。然后使用各种可用的标志、宽度和精度打印返回的字符串"%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);
}
Output
base10: 0 base2: 0 base36:0 0
base10: 25 base2:11001 base36:P 25
base10:4294967295 base2:11111111111111111111111111111111 base36:1Z141Z3 4294967295
Ref: 有 printf 转换器可以以二进制格式打印吗? https://stackoverflow.com/q/111928/2410359有很多答案,但没有一个答案允许简单的内存管理(没有static
)上述内容可以访问fprintf()
标志宽度、精度和使用数量的全范围。
这是一回答你自己的问题 https://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/ answer.