escafia <[EMAIL PROTECTED]> 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

_______________________________________________
Haskell-Cafe mailing list
[email protected]
http://www.haskell.org/mailman/listinfo/haskell-cafe

Reply via email to