Skip to content

Instantly share code, notes, and snippets.

@dermesser
Created August 7, 2013 18:46
Show Gist options
  • Save dermesser/6177180 to your computer and use it in GitHub Desktop.
Save dermesser/6177180 to your computer and use it in GitHub Desktop.
Haskell code to convert decimal numbers to a digital representation ([Digital]) and vice versa.
-- Dec2Bin
--
data Digital = D1 | D0
instance Show Digital where
show D1 = "1"
show D0 = "0"
instance Eq Digital where
D1 == D1 = True
D0 == D0 = True
_ == _ = False
dec2bin :: Integer -> [Digital]
dec2bin n = fragmentDec n $ smallestPowerOf2ToFit n
fragmentDec :: Integer -> Integer -> [Digital]
fragmentDec _ (-1) = []
fragmentDec n p = (getDig matches):(fragmentDec (if matches then n-digval else n) (p-1))
where matches = ((fromIntegral n)/(2^p)) >= 1
getDig b
| b == True = D1
| b == False = D0
digval = 2^p
smallestPowerOf2ToFit :: Integer -> Integer
smallestPowerOf2ToFit n = sPO2TF n 0
where sPO2TF n p = if ((fromIntegral n)/(fromIntegral $ 2^p)) >= 1
then sPO2TF n (p+1)
else p-1
-- Bin2Dec
bin2dec :: [Digital] -> Integer
bin2dec [] = 0
bin2dec l@(x:xs)
| x == D1 = 2^(len-1) + bin2dec xs
| x == D0 = bin2dec xs
where len = length l
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment