Created
August 26, 2017 16:46
-
-
Save koru1130/4fea4b659159b0a16493f223c5885598 to your computer and use it in GitHub Desktop.
For Practice
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE ScopedTypeVariables #-} | |
module Main (main) where | |
import Data.List() | |
import Data.String() | |
import Data.List.Split | |
import Data.Function | |
import Data.Maybe | |
import System.Environment | |
main = do | |
args <- getArgs | |
putStrLn $ base64encode $ head args | |
intToBase64 = (fromJust.) $ flip lookup $ zip [0..63] "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" | |
base64ToInt = (fromJust.) $ flip lookup $ zip "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" [0..63] | |
base64encode :: String -> String | |
base64encode = concatMap translate . chunksOf 6 . concatMap (toBits8 . fromEnum) | |
translate x = | |
(intToBase64 . binToInt) x : case length x of | |
2 -> "==" | |
4 -> "=" | |
6 -> "" | |
binToInt :: [Bool] -> Int | |
binToInt = sum . mulWeight . map fromEnum | |
where | |
mulWeight = map (\(i,x)->x * 2^i) . zip [0..] . reverse | |
boolToString :: Bool -> String | |
boolToString True = "1" | |
boolToString False = "0" | |
toBitsBySize :: forall a t. (Integral t, Integral a) => t -> a -> [Bool] | |
toBitsBySize 0 x = [] | |
toBitsBySize sz 0 = [False | i <- [1..sz]] | |
toBitsBySize sz x = if k == 0 | |
then False : toBitsBySize n x | |
else True : toBitsBySize n (x - k*m) | |
where n = sz - 1 | |
m = 2^n | |
k = x `div` m | |
toBits8 = toBitsBySize 8 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment