Skip to content

Instantly share code, notes, and snippets.

@dajare
Last active January 3, 2021 18:25
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dajare/721c1ca973d7325efb69ba71b5731920 to your computer and use it in GitHub Desktop.
Save dajare/721c1ca973d7325efb69ba71b5731920 to your computer and use it in GitHub Desktop.
Shell script to convert unix timestamp to base36 (alphanumeric, lowercase)
#!/bin/bash
# takes unix timestamp and converts to base36
# ht: https://en.wikipedia.org/wiki/Base36#bash_implementation
value=$(date +%s)
result=""
base36="0123456789abcdefghijklmnopqrstuvwxyz"
while true; do
result=${base36:((value%36)):1}${result}
if [ $((value=${value}/36)) -eq 0 ]; then
break
fi
done
echo ${result}
@dajare
Copy link
Author

dajare commented Jan 28, 2018

Don't forget to chmod 755 !

Also change last line to

echo ${result: -4}

to return last four characters.

Examples of Output:

  • date +%s = 1517218014
  • base36 = p3a53y
  • last 4 = a53y

@caorongjin
Copy link

What about: date +%s | openssl base64?

@dajare
Copy link
Author

dajare commented Jan 30, 2018

Thanks @caorongjin -- I actually even tried that! 😉 But it gives me this result:

$ date +%s | openssl base64
MTUxNzMwMDIyNwo=

That's a long string! And it seems you need the last 5 characters to be clear of clashes.
It's a nice one-liner 👏 but I'm struggling to see how the output is an advantage.

Oddly, checking the Convert^xy site, their Base64 result for a unix timestamp type decimal input is BacC4T -- same length as my "base 36" result, but last four characters would have reduced likelihood of clashes, I suppose. Now, I ask myself, why does the openssl crypto encoding give me such a long result?

@caorongjin
Copy link

Well, yes, you need to cut the last 4 out (minus any '=' padding). Is this one better:

date +%s | openssl base64 | sed 's/=//' | tail -c -5
xOAo

For some reason, there seems to be trailing whitespace so I need a -5 instead of a -4.

Why Convert^xy does that, beats me. And yes, if Typora is case insensitive… that's just, well, insensitive.

@dajare
Copy link
Author

dajare commented Jan 30, 2018

@caorongjin said:

And yes, if Typora is case insensitive… that's just, well, insensitive.

LOL. @typora actually is a bit weird in handling case differences. I'll do a bit of testing, and if I can work out the pattern, will post a bug report.

@roblogic
Copy link

Nice base36 converter.

The openssl (and unix) base64 algorithm is for encoding binary data into ASCII strings, not for converting integers to different radix (numeric base). https://en.wikipedia.org/wiki/Base64

To convert an integer to an exotic numeric base you'll need something like these: https://stackoverflow.com/questions/14471692/bash-decimal-to-base-62-conversion

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment