1

我有一个应用程序,用户必须记住并插入一个像 1221931027 这样的 unix 时间戳。为了更容易记住密钥,我喜欢通过允许字符 [az] 来减少要插入的字符数。所以我正在寻找一种算法来将时间戳转换为更短的字母数字版本并向后执行相同的操作。有什么提示吗?

4

4 回答 4

5

您可以将时间戳转换为 base-36。

于 2008-09-20T17:31:37.610 回答
2
#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
*/
于 2008-09-20T18:51:48.447 回答
0

将时间戳转换为十六进制。这将从时间戳中为您生成一个较短的字母数字数字。

于 2008-09-20T17:34:25.623 回答
0

有时用于此类事情的另一种选择是使用音节列表。IE。你有一个音节列表,如 ['a','ab','ba','bi','bo','ca','...] 并将数字转换为 base(len(list_of_syllables))。这在字母方面更长,但通常更容易记住诸如“flobagoka”之类的内容而不是诸如“af3q5jl”之类的内容。(缺点是很容易生成听起来像亵渎的单词)

[编辑] 是这种算法的一个例子。使用这个,1221931027 将是“buruvadrage”

于 2008-09-20T18:51:21.210 回答