[Haskell-cafe] int to bin, bin to int

Don Stewart dons at galois.com
Thu Sep 27 18:25:08 EDT 2007


prstanley:
> Hi
> intToBin :: Int -> [Int]
> intToBin 1 = [1]
> intToBin n = (intToBin (n`div`2)) ++ [n `mod` 2]
> 
> binToInt :: [Integer] -> Integer
> binToInt [] = 0
> binToInt (x:xs) = (x*2^(length xs)) + (binToInt xs)

> Any comments and/or criticisms on the above definitions would be 
> appreciated.

One of my favourites is:

    unroll :: Integer -> [Word8]
    unroll = unfoldr step
      where
          step 0 = Nothing
          step i = Just (fromIntegral i .&. 1, i `shiftR` 1)

    roll :: [Word8] -> Integer
    roll   = foldr unstep 0 
      where
          unstep b a = a `shiftL` 1 .|. fromIntegral b

-- Don


More information about the Haskell-Cafe mailing list