views:

670

answers:

3

How to print integer literals in binary or hex in haskell?

printBinary 5 => "0101"

printHex 5 => "05"

Which libraries/functions allow this?

I came across the Numeric module and its showIntAtBase function but have been unable to use it correctly.

> :t showIntAtBase 

showIntAtBase :: (Integral a) => a -> (Int -> Char) -> a -> String -> String
A: 

you can convert integer to binary with this code or like this code :

decToBin x = reverse $ decToBin' x
where
decToBin' 0 = []
decToBin' y = let (a,b) = quotRem y 2 in [b] ++ decToBin' a

usage:

decToBin 10 => [1,0,1,0]
SjB
i see you googled this.
Jonno_FTW
congratulation :D Don't be tired
SjB
+7  A: 

The Numeric module includes several functions for showing an Integral type at various bases, including showIntAtBase. Here are some examples of use:

putStrLn $ showHex 12 "" -- prints "c"
putStrLn $ showIntAtBase 2 intToDigit 12 "" -- prints "1100"
Chuck
+6  A: 

If you import the Numeric and Data.Char modules, you can do this:

showIntAtBase 2 intToDigit 10 "" => "1010"
showIntAtBase 16 intToDigit 1023 "" => "3ff"

This will work for any bases up to 16, since this is all that intToDigit works for. The reason for the extra empty string argument in the examples above is that showIntAtBase returns a function of type ShowS, which will concatenate the display representation onto an existing string.

Ian Ross