Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Haskell

Idiom #76 Binary digits from an integer

Create the string s of integer x written in base 2.

E.g. 13 -> "1101"

import Data.List
foldl (\acc -> (++ acc) . show) "" . unfoldr (\n -> if x == 0 then Nothing else Just (x `mod` 2, x `div` 2))

Sure, it will produce the empty string for 0 but it's a catamorphism composed with an anamorphism... I mean how much more Haskell-y do you get? There's even some currying and partial application in there!
import Numeric (showIntAtBase)
import Data.Char (intToDigit)
s x = showIntAtBase 2 intToDigit x ""
(:require [clojure.pprint])
(defn s
  [x]
  (pprint/cl-format nil "~b" x))

Call s and pass an integer x to it and it will return your integer in base 2.

New implementation...