1 {- 2 - BinConv.hs 3 - 4 - Paul Sanders, SRD. 1992 5 - 6 - This module contains routines for converting numbers to and from a 7 - number of binary digits. 8 - 9 -} 10 11 module BinConv (codes_to_ascii, ascii_to_codes, dec_to_binx) where 12 13 zeroes = '0' : zeroes 14 15 -- dec_to_binx converts a decimal to a fixed number of binary digits 16 -- dec_to_binx #binary-digits decimal-number = binary-string 17 18 dec_to_binx :: Int -> Int -> String 19 dec_to_binx x y 20 = take (x - length bin_string) zeroes ++ bin_string 21 where 22 bin_string = dec_to_bin y 23 24 dec_to_bin = reverse . dec_to_bin' 25 26 dec_to_bin' 0 = [] 27 dec_to_bin' x 28 = (if (x `rem` 2) == 1 29 then '1' 30 else '0') : dec_to_bin' (x `div` 2) 31 32 codes_to_ascii :: [Int] -> [Int] 33 codes_to_ascii [] = [] 34 codes_to_ascii (x:y:ns) 35 = x_div : ((x_rem * 16) + y_div) : y_rem : codes_to_ascii ns 36 where 37 (x_div, x_rem) = divRem x 16 38 (y_div, y_rem) = divRem y 256 39 codes_to_ascii [n] 40 = [x_div , x_rem] 41 where 42 (x_div, x_rem) = divRem n 16 43 44 ascii_to_codes [] = [] 45 ascii_to_codes (x:y:z:ns) 46 = (x * 16) + y_div : (y_rem * 256) + z : ascii_to_codes ns 47 where 48 (y_div, y_rem) = divRem y 16 49 ascii_to_codes [x,y] 50 = [(x * 16) + y_rem] 51 where 52 (y_div, y_rem) = divRem y 16 53 54 divRem x y = (x `div` y, x `rem` y) -- missing from PreludeCore ?