c - 将代码从 5 位转换为 3 个字符
问题描述
我有一个由五位小数组成的代码,我需要将它存储(压缩)在一个只能包含 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;
}
推荐阅读
- javascript - 使用Javascript添加innerHTML
- clojure - 什么是:<> 试剂打嗝?
- flutter - 如何实现 CircularProgressIndicator 对话框和“已发送消息!” Flutter 中的对话框?
- javascript - TypeError:无法解构“this.props.Name”的属性“id”,因为它未定义。在 ReactJS 中
- bash - 打印正确的 MHz 或 GHZ 数取决于 CPU 缩放
- angular - RemveAt删除项目后的Angular Reactive Form,将自动创建新项目
- r - 在 R 中处理大型数据集(Sentinel 2)
- c# - 如何修复 TextBox 的方向以始终留在 C# 中?
- javascript - MessageBird 全渠道小部件 - 单页 Web 应用程序 - 错误
- java - 如何将元信息添加到 xtext 生成的文件