Decimal to Binary[29 Jun 2010]

Python Environment

Introducing

Python has no builtin functions to convert decimal integers to binary, something like "int()" or "hex()" do. So we have to build it by ourselves.

Binary numbers

Actually, I could write down a mathematics lesson, but why do it if wikipedia does exist? :) Check it out!  http://en.wikipedia.org/wiki/Binary_numeral_system

My script

Below my own script, maybe not so elegant but clear.

#/usr/bin/env python

# this script convert a decimal number to a binary
import exceptions, sys, random

def to_binary(num):
  try:
    num = int(num)
  except Exception, msg:
    print >> sys.stderr, "Error: the passed paramether is not a number."
    print >> sys.stderr, "Details:", msg
    exit(1)

  # build the binary number
  rbin = ""
  while num != 0:
    if num % 2 == 1:
      rbin += "1"
    else:
      rbin += "0"
    num = num / 2

  # turn the string upside down
  binary = ""
  for i in range(len(rbin)-1, -1, -1):
    binary += rbin[i]
  return binary

if __name__ == "__main__":
  serie = range(100)
  random.shuffle(serie)
  n = serie[0]
  print "Trying to convert decimal", n, "to binary..."
  print "result = ", to_binary(n)
  exit(0)

Consider that my function returns a string. This is very good considering that functions like "int()" ask a string value as argumenet: you can easily apply the revers operation.