Skip to content

Instantly share code, notes, and snippets.

@thomascrenshaw
Last active November 18, 2020 19:07
Show Gist options
  • Save thomascrenshaw/7017956 to your computer and use it in GitHub Desktop.
Save thomascrenshaw/7017956 to your computer and use it in GitHub Desktop.
base 36 () functions in various languages
# php
<?php print base_convert("12abcxyz",36,10); ?>
----
#python
def base36encode(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
"""Converts an integer to a base36 string."""
if not isinstance(number, (int, long)):
raise TypeError('number must be an integer')
base36 = ''
sign = ''
if number < 0:
sign = '-'
number = -number
if 0 <= number < len(alphabet):
return sign + alphabet[number]
while number != 0:
number, i = divmod(number, len(alphabet))
base36 = alphabet[i] + base36
return sign + base36
def base36decode(number):
return int(number, 36)
print base36encode(1412823931503067241)
print base36decode('AQF8AA0006EH')
----
# javascript
(1234567890).toString(36) // => "kf12oi"
parseInt("kf12oi",36) // => 1234567890
----
SOURCE: http://en.wikipedia.org/wiki/Base_36
----
# math example
(FACE)36 = 15*363 + 10*362 + 12*36 + 14.
SOURCE: http://primes.utm.edu/notes/words.html
USES IN PRACTICE:
tinyurl -- use base 36 integers as compact alphanumeric identifiers
reddit -- uses base-36 for identifying posts and comments.
INTERESTING
http://primes.utm.edu/notes/words.html - prime numbers that are words in Base36
WIKIPEDIA (Base36) == 91,730,738,691,298 (decimal)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment