[Haskell-cafe] Binary code

Mark T.B. Carroll mark at ixod.org
Mon Nov 27 19:46:32 EST 2006


escafia <escafia at gmail.com> writes:

> Hi, 
>
> i've one fuction receiving an int . The objective is return the respective
> binary code of that int.
>
> For example, if i receive 28 the fuction will return 011100.

In GHCi,

Prelude> Numeric.showIntAtBase 2 (head . show) 28 $ ""
"11100"

> My question is that there is any fuction in libraries that do this?
> If not, anyone has any suggestion?

Other alternatives include,

import Data.Bits
import Data.List

toBinary 0 = "0"

toBinary i =
    reverse (unfoldr nextDigit i)
    where
      nextDigit 0 = Nothing
      nextDigit i = Just (head (show (i .&. 1)), shiftR i 1)

or maybe, as you seem to want a certain number of digits,

toBinary d i =
    concatMap show [ fromEnum (testBit i n) | n <- reverse [0..d-1] ]

or likewise will work.

It's probably best to just use showIntAtBase and pad it with however
many 0's you want, though.

-- Mark



More information about the Haskell-Cafe mailing list