c - 将代码从 5 位数字转换为 3 个字符

标签 c algorithm math compression

我有一个由五位十进制组成的代码,我需要将其存储(压缩)在只能包含 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/

相关文章:

c - 当我点击我的子窗口时,为什么我得到 WM_MOUSEACTIVATE?我让它把焦点转移到 parent 身上,这会搞砸 child 杀死焦点逻辑

java - 优化两个列表的比较和合并

c - 修改给定的数字以找到所需的总和?

c - 错误时返回 -1 的替代方法

math - 只需要前 k 位数字时的快速求幂?

当我除两个变量时,C 程序输出错误

c - 如何修改已传递给 C 函数的指针?

c - 对 `stack_init' 的 undefined reference

algorithm - 文件比较策略

c# - List<T> 中使用了哪种算法来动态分配内存?