Reputation:
I have an application where a user has to remember and insert an unix timestamp like 1221931027. In order to make it easier to remember the key I like to reduce the number of characters to insert through allowing the characters [a-z]. So I'm searching for an algorithm to convert the timestamp to a shorter alphanum version and do the same backwards. Any hints?
Upvotes: 1
Views: 1537
Reputation: 119301
Another option sometimes used for things like this is to use lists of syllables. ie. you have a list of syllables like ['a','ab', 'ba','bi','bo','ca','...] and transform the number into base(len(list_of_syllables)). This is longer in terms of letters, but it can often be easier to memorise something like "flobagoka' than something like 'af3q5jl'. (The downside is that it can be easy to generate words that sound like profanity)
[Edit] Here's an example of such an algorithm. Using this, 1221931027 would be "buruvadrage"
Upvotes: 0
Reputation: 517
#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
*/
Upvotes: 2
Reputation: 37850
convert the timestamp to HEX. That will generate a shorter alphanumeric number for you out of the timestamp.
Upvotes: 0