将时间戳转换为alphanum

时间:2008-09-20 17:29:38

标签: algorithm time

我有一个应用程序,用户必须记住并插入像1221931027这样的unix时间戳。为了更容易记住密钥,我希望通过允许字符[a-z]减少要插入的字符数。所以我正在寻找一种算法来将时间戳转换为更短的alphanum版本并向后做同样的事情。任何提示?

4 个答案:

答案 0 :(得分:5)

您只需将时间戳转换为base-36。

答案 1 :(得分: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
*/

答案 2 :(得分:0)

将时间戳转换为HEX。这将在时间戳之外为您生成一个更短的字母数字。

答案 3 :(得分:0)

有时用于此类事情的另一个选项是使用音节列表。即。你有一个音节列表,如['a','ab','ba','bi','bo','ca','...],并将数字转换为base(len(list_of_syllables))。这在字母方面比较长,但通常更容易记住像“flobagoka”之类的东西而不是像'af3q5jl'那样的东西。(缺点是它可以很容易地产生听起来像亵渎的词语)

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

相关问题