Changing a decimal into a binary

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Bemoox
    New Member
    • Sep 2013
    • 1

    Changing a decimal into a binary

    So yeah I'm kind of new to python and I wanted to know how to change a decimal to binary
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    The following function uses built-in function divmod and recursion:
    Code:
    def dec2bin(num):
        ''' Convert a decimal integer to base 2.'''
        if num == 0:
            return ''
        num, rem = divmod(num, 2)
        return dec2bin(num)+str(rem)
    Code:
    >>> dec2bin(1234)
    '10011010010'

    Comment

    • dwblas
      Recognized Expert Contributor
      • May 2008
      • 626

      #3
      Python has a built in also
      Code:
       print bin(1234)
      0b10011010010

      Comment

      Working...