Published on
Fri Jan 24, 2014

EPI 5.9 - Elias Encoding and Decoding

Problem

Elias encoded version of an integer X = X in binary PREPENDED by number of zeroes in the binary representation minus 1.

So Elias of encoding of 13 (binary = 1101) would be 000 1101 (3 zeroes as length of 1101 = 4).

Solution

 1elias_encode_int :: Int -> [Char]
 2elias_encode_int x = (take (len - 1) (repeat '0')) ++ xbase2
 3    where
 4        xbase2  = intToString 2 x
 5        len     = (length xbase2)
 6
 7
 8elias_decode_str :: Int -> [Char] -> Int
 9elias_decode_str size xs = stringToInt 2 (take size xs)
10
11
12elias_encode :: [Int] -> [Char]
13elias_encode xs = concat (map elias_encode_int xs)
14
15
16elias_decode_helper :: Int -> [Char] -> [Int]
17elias_decode_helper  nzeroes [] = []
18elias_decode_helper  nzeroes (f:fs)
19        | f == '0' = elias_decode_helper  (1 + nzeroes) fs
20        | otherwise = (elias_decode_str (1 + nzeroes) (f:fs)) : (elias_decode_helper  0 (drop nzeroes fs))
21
22
23elias_decode = elias_decode_helper 0