我有一个由五位十进制组成的代码,我需要将其存储(压缩)在只能包含 3 个字母数字 ascii 可打印字符的字段中。两个字段之间是否可以进行双向转换?在 C 中如何实现?
最佳答案
要使用三位数表示 0 到 99999 之间的任何数字,您需要将数字从基数 10 转换为更高的基数 b,其中 b 3> 99999。
满足此要求的最小基数是 47。有 97 个可打印 ASCII 字符可供选择,所以显然没有问题。
顺便说一句,如果您要将数字转换为用户可见的字符串,您可能需要考虑选择那些不可能形成不幸的字符串(例如 bum
)的字符。
下面的代码应该可以工作。它尚未优化,但应该足够快,除非您需要每秒转换数百万个数字。
#define ALPHABET "26789BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz"
#define LEN_ALPH 47
unsigned int asc2int(char *s) {
unsigned int i, result = 0;
while (*s) {
for (i=0; i<LEN_ALPH; i++) {
if (*s == ALPHABET[i]) break;
}
if (i == LEN_ALPH) return 0; /* Illegal character in input */
result = result * LEN_ALPH + i; /* TODO: Check for overflow */
s++;
}
return result;
}
char *int2asc(unsigned int n) {
static char result[7]; /* Should be sufficient for any 32-bit input */
char *ptr = result+6;
*ptr = '\0';
if (n == 0) {
*(--ptr) = ALPHABET[0];
}
else {
while (n) {
*(--ptr) = ALPHABET[n % LEN_ALPH];
n /= LEN_ALPH;
}
}
return ptr;
}
int main() {
unsigned int tests[10] = { 0, 1, 10, 100, 1000, 10000, 11111, 12345, 54321, 99999 };
unsigned int i, n;
char *s;
/* Test with selected numbers */
for (i=0; i<10; i++) {
s = int2asc(tests[i]);
n = asc2int(s);
printf("%u -> %s -> %u\n", tests[i], s, n);
}
/* Test all numbers */
for (i=0; i<100000; i++) {
if (asc2int(int2asc(i)) != i) {
printf("Failed at i=%u\n", i);
return 1;
}
}
return 0;
}
关于c - 将代码从 5 位数字转换为 3 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50581915/