将整数转换为字符
我想OP想要的不仅仅是1位数字的转换,因为提供了 radix
。
将一个int转换为string(不仅限于一个char),可以使用sprintf(buf, "%d", value)方法。
要将其转换为任何基数,需要处理字符串管理问题以及处理INT_MIN的特殊情况。
以下是C99解决方案,返回一个
char*
,其生命周期有效到块的结尾。通过宏提供
复合字面量来实现这一点。
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define ITOA_BASE_N (sizeof(unsigned)*CHAR_BIT + 2)
char *itoa_base(char *s, int x, int base) {
s += ITOA_BASE_N - 1;
*s = '\0';
if (base >= 2 && base <= 36) {
int x0 = x;
do {
*(--s) = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[abs(x % base)];
x /= base;
} while (x);
if (x0 < 0) {
*(--s) = '-';
}
}
return s;
}
#define TO_BASE(x,b) itoa_base((char [ITOA_BASE_N]){0} , (x), (b))
使用示例和测试
void test(int x) {
printf("base10:% 11d base2:%35s base36:%7s ", x, TO_BASE(x, 2), TO_BASE(x, 36));
printf("%ld\n", strtol(TO_BASE(x, 36), NULL, 36));
}
int main(void) {
test(0);
test(-1);
test(42);
test(INT_MAX);
test(-INT_MAX);
test(INT_MIN);
}
输出
base10: 0 base2: 0 base36: 0 0
base10: -1 base2: -1 base36: -1 -1
base10: 42 base2: 101010 base36: 16 42
base10: 2147483647 base2: 1111111111111111111111111111111 base36: ZIK0ZJ 2147483647
base10:-2147483647 base2: -1111111111111111111111111111111 base36:-ZIK0ZJ -2147483647
base10:-2147483648 base2: -10000000000000000000000000000000 base36:-ZIK0ZK -2147483648
参考 如何使用复合字面量以任意进制向fprintf()
输出多个格式化数字?
10
转换为字母'A'
,可能是基于十六进制数字的转换方式。您是否期望使用十六进制数字进行转换? - Barmar