Skip to content

Instantly share code, notes, and snippets.

@MiyamonY
Created March 7, 2015 08:17
Show Gist options
  • Save MiyamonY/082478cd36377dfb739a to your computer and use it in GitHub Desktop.
Save MiyamonY/082478cd36377dfb739a to your computer and use it in GitHub Desktop.
haskell StrConverter
import Data.Char (ord, chr)
type Bit = Int
bin2int :: [Bit] -> Int
bin2int bits = sum [w * b | (w, b) <- zip weights bits]
where weights = iterate (* 2) 1
int2bin :: Int -> [Bit]
int2bin 0 = []
int2bin n = r : int2bin q
where (q, r) = quotRem n 2
make8 :: [Bit] -> [Bit]
make8 bits = take 8 (bits ++ repeat 0)
encode :: String -> [Bit]
encode = concat . map (make8 . int2bin . ord)
chop8 :: [Bit] -> [[Bit]]
chop8 [] = []
chop8 bits = take 8 bits : (chop8 . drop 8 $ bits)
decode :: [Bit] -> String
decode = map (chr . bin2int) . chop8
channel :: [Bit] -> [Bit]
channel = id
transmit :: String -> String
transmit = decode . channel . encode
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment