将时间戳转换为字母数字
时间:2020-03-06 14:29:20 来源:igfitidea点击:
我有一个应用程序,用户必须记住该应用程序并插入一个像1221931027这样的unix时间戳。为了更容易记住键,我想通过允许字符[a-z]来减少要插入的字符数。因此,我正在寻找一种将时间戳转换为较短的alphanum版本并向后进行相同操作的算法。有什么提示吗?
解决方案
我们可以将时间戳转换为以36为基数的时间戳。
将时间戳转换为十六进制。这将在时间戳之外为我们生成一个较短的字母数字。
有时用于此类情况的另一种选择是使用音节列表。 IE。我们有一个音节列表,例如['a','ab','ba','bi','bo','ca','...],然后将数字转换为base(len(list_of_syllables))。就字母而言,这要更长一些,但记住" flobagoka"之类的单词通常要比" af3q5jl"之类的单词更容易记住(缺点是它容易产生听起来像亵渎的单词)
[编辑]这是这种算法的示例。使用它,1221931027将是" buruvadrage"
#include <time.h>
#include <stdio.h>
// tobase36() returns a pointer to static storage which is overwritten by
// the next call to this function.
//
// This implementation presumes ASCII or Latin1.
char * tobase36(time_t n)
{
static char text[32];
char *ptr = &text[sizeof(text)];
*--ptr = 0; // NUL terminator
// handle special case of n==0
if (n==0) {
*--ptr = '0';
return ptr;
}
// some systems don't support negative time values, but some do
int isNegative = 0;
if (n < 0)
{
isNegative = 1;
n = -n;
}
// this loop is the heart of the conversion
while (n != 0)
{
int digit = n % 36;
n /= 36;
*--ptr = digit + (digit < 10 ? '0' : 'A'-10);
}
// insert '-' if needed
if (isNegative)
{
*--ptr = '-';
}
return ptr;
}
int main(int argc, const char **argv)
{
int i;
for (i=1; i<argc; ++i)
{
long timestamp = atol(argv[i]);
printf("%12d => %8s\n", timestamp, tobase36(timestamp));
}
}
/*
$ gcc -o base36 base36.c
$ ./base36 0 1 -1 10 11 20 30 35 36 71 72 2147483647 -2147483647
0 => 0
1 => 1
-1 => -1
10 => A
11 => B
20 => K
30 => U
35 => Z
36 => 10
71 => 1Z
72 => 20
2147483647 => ZIK0ZJ
-2147483647 => -ZIK0ZJ
*/

