### Converting decimal integers to binary strings in different languages

This is a fun post, telling the tale of a simple programming challenge taken in a number of different languages to learn those languages. The challenge is simple: write a function that, given an integer input, will return the binary representation of that number. To start you can assume that the number you have been given is positive, but you can handle negative numbers for extra credit.

Let’s start with C#:

public static string IntToBinary(int i) { var resultBuilder = new StringBuilder(); do { var bit = i % 2; resultBuilder.Insert(0, bit.ToString()); i = i / 2; } while (i > 0); return resultBuilder.ToString(); }

As you can see, this is a very procedural way of thinking. It’s got a StringBuilder, a conventional loop… Not that pretty. We can do this much more succinctly, but it illustrates the basic procedure for converting a number to binary. You can find the final (right-most) bit of the binary representation by modding the number by 2. To find the right-most-but-one bit, you divide the number by 2 (discarding any result) and then mod the result by 2. Continue until you eventually end up with zero.

Let’s switch language. How about something more functional, like F#?

let rec intToBinary i = match i with | 0 | 1 -> string i | _ -> let bit = string (i % 2) (intToBinary (i / 2)) + bit

This looks better! What’s different here? First of all we have changed the function to a recursive one.

What about a language like CoffeeScript or, even better, Livescript?

int-to-binary = (i) ->

| i in [0, 1] => i

| _ => "#{int-to-binary i .>>. 1}#{i % 2}"

As usual Livescript produces the shortest code.