Skip to content

Instantly share code, notes, and snippets.

@hallettj
Created August 25, 2012 21:56
Show Gist options
  • Save hallettj/3471332 to your computer and use it in GitHub Desktop.
Save hallettj/3471332 to your computer and use it in GitHub Desktop.
Haskell library to convert unsigned integers to and from base36 representations
-- Converts unsigned integers to and from base36 representations
module Numeric.Base36 (
readBase36
, showBase36
) where
import Data.Char (isAscii, isLetter, isDigit, ord, chr, toLower)
import Numeric (readInt, showIntAtBase)
readBase36 :: (Integral a) => String -> [(a, String)]
readBase36 = readInt 36 isAsciiAlphaNum digitToInt
showBase36 :: (Integral a, Show a) => a -> String -> String
showBase36 = showIntAtBase 36 intToDigit
isAsciiAlphaNum :: Char -> Bool
isAsciiAlphaNum c = isAscii c && (isDigit c || isLetter c)
-- Slightly modified from the hexadecimal implementation in Data.Char
digitToInt :: Char -> Int
digitToInt c
| isDigit c = ord c - ord '0'
| c >= 'a' && c <= 'z' = ord c - ord 'a' + 10
| c >= 'A' && c <= 'Z' = ord c - ord 'A' + 10
| otherwise = error ("Base36.digitToInt: not a digit " ++ show c) -- sigh
intToDigit :: Int -> Char
intToDigit n
| n < 10 = chr (n + ord '0')
| otherwise = chr (n + ord 'a' - 10)
@munro
Copy link

munro commented Aug 26, 2012

(78857554403044).toString(36)

Another win for JavaScript! (p.s. parseInt that with radix 36)

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