Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 577
TheOne Avatar asked Dec 24 '09 20:12

TheOne


2 Answers

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

import Numeric (showHex, showIntAtBase)
import Data.Char (intToDigit)

putStrLn $ showHex 12 "" -- prints "c"
putStrLn $ showIntAtBase 2 intToDigit 12 "" -- prints "1100"
like image 100
Chuck Avatar answered Sep 21 '22 00:09

Chuck


You may also use printf of the printf package to format your output with c style format descriptors:

import Text.Printf

main = do

    let i = 65535 :: Int

    putStrLn $ printf "The value of %d in hex is: 0x%08x" i i
    putStrLn $ printf "The html color code would be: #%06X" i
    putStrLn $ printf "The value of %d in binary is: %b" i i

Output:

The value of 65535 in hex is: 0x0000ffff
The html color code would be: #00FFFF
The value of 65535 in binary is: 1111111111111111

like image 38
Martin Lütke Avatar answered Sep 18 '22 00:09

Martin Lütke