[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:
> 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.
Prelude> Numeric.showIntAtBase 2 (head . show) 28 $ ""
> My question is that there is any fuction in libraries that do this?
> If not, anyone has any suggestion?
Other alternatives include,
toBinary 0 = "0"
toBinary i =
reverse (unfoldr nextDigit i)
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.
More information about the Haskell-Cafe