summaryrefslogtreecommitdiff
path: root/base64/base64_0.hs
blob: f7673b8ee44c91a0a5c82b5fb602bc048e92e82b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
-- File: base64.hs --
 
import Data.Char
import Text.Printf
import qualified Data.List as L
import qualified Data.List.Split as T
 
toBase64 x      = maskBase64 x . toBase64core . asciiToBin . binFill $ x
toBase64core    = map base64toDigit . map binToDec . T.chunksOf 6
 
base64toDigit x = (['A'..'Z']++['a'..'z']++['0'..'9']++['+','/']) !! x
binToDec        = sum . map (2^) . L.findIndices (=='1') . reverse
asciiToBin      = concat . map (\y -> printf "%08b" y) . map ord 
binFill x       = x ++ (take (fill64length x) $ cycle "\000")
 
maskBase64 o x  = take (length x - l ) x ++ (take l $ cycle "=")
                  where l = (fill64length o)
 
fill64length x | m==0      = 0
               | otherwise = 3-m
               where m=mod (length x) 3
 
main = do
    line <- getLine
    putStrLn $ toBase64 line