need help converting decimal numbers to binary and vice versa

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • victory2006
    New Member
    • Nov 2008
    • 10

    need help converting decimal numbers to binary and vice versa

    like we have an integer value of : 9
    and i need to convert it to binary numbers

    and vice versa, thanks!
  • victory2006
    New Member
    • Nov 2008
    • 10

    #2
    oh wait, how about this..
    a list:
    [0, 0, 1, 1]

    i need to make it so that it will read that as 0011, so that i will be a binary number.

    so i need [0, 0, 1, 1] to equal 0011

    THEN i need help to convert 0011 into base 10...THANKS

    Comment

    • victory2006
      New Member
      • Nov 2008
      • 10

      #3
      well i did this,
      Code:
      for a in patrow2:
              print "      "
              for b in a:
                   print b,
      OUTPUT:
      **
      1 0 0
      1 1 0
      1 1 0
      **
      patrow2 is the list of lists , which in this case is [[1, 0, 0], [1, 1, 0], [1, 1, 0]]

      but how do u get rid of the spaces in between the numbers?

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        Originally posted by victory2006
        well i did this,
        Code:
        for a in patrow2:
                print "      "
                for b in a:
                     print b,
        OUTPUT:
        **
        1 0 0
        1 1 0
        1 1 0
        **
        patrow2 is the list of lists , which in this case is [[1, 0, 0], [1, 1, 0], [1, 1, 0]]

        but how do u get rid of the spaces in between the numbers?
        Following are two ways:
        Code:
        >>> patrow2 = [[1, 0, 0], [1, 1, 0], [1, 1, 0]]
        >>> for item in patrow2:
        ... 	print ''.join([str(i) for i in item])
        ... 	
        100
        110
        110
        >>> for item in patrow2:
        ... 	print '%d%d%d' % tuple(item)
        ... 	
        100
        110
        110
        >>>
        To convert from binary to decimal, use built-in function int().

        Code:
        >>> int('011', 2)
        3
        >>>

        Comment

        • MorseCode
          New Member
          • Dec 2008
          • 3

          #5
          Something I whipped up once to convert decimal to binary:

          Code:
          def dec2biprog():
              empt = ""
              def dec2bi(x):
                  y = empt
                  z = 0
                  power = range(1, 51)
                  power.reverse()
                  for i in power:
                      power[z] = 2**power[z]
                      z = z + 1
                  power.append(1)
                  for i in power:
                      if x >= i:
                          x = x - i
                          y = y + "1"
                      else:
                          y = y + "0"
                  a = 0
                  for i in y:
                      if i == "0":
                          a = a + 1
                      elif i == "1":
                          return y[a:100]
          And the UI:

          Code:
              print """Welcome to D2B, the program that converts your decimal
              (or base 10) numbers into binary (or base 2) numbers.
              """
              erone = 0
              while True:
                  inp = raw_input("Please enter your number here: ")
                  print empt
                  try:
                      if inp == "0" or int(inp) < 0:
                          print "Please pick a number greater than 0!"
                          erone = 1
                  except ValueError:
                      print "Pick a number!"
                      erone = 1
                  if erone != 1:
                      if int(inp) > 1125899906842624:
                          print "Pick a number less than 1,125,899,906,842,625, please."
                          erone = 1
                  if erone != 1:
                      print "Your number, " + str(inp) + ", is " + dec2bi(int(inp)) + " in binary!"
                  else:
                      erone = 0
                  print empt
                  ertest = 0
          dec2biprog()

          Comment

          • bvdet
            Recognized Expert Specialist
            • Oct 2006
            • 2851

            #6
            MorseCode,

            Thank you for sharing your code with us. You can streamline your code a bit by using range() with a negative step in a list comprehension.
            Original code:
            Code:
                    z = 0
                    power = range(1, 51)
                    power.reverse()
                    for i in power:
                        power[z] = 2**power[z]
                        z = z + 1
                    power.append(1)
            Recommended code:
            Code:
                    power = [2**i for i in range(50, -1, -1)]

            You are removing the leftmost "0"s with a for loop. You can use string method lstrip() for this.
            Original code:
            Code:
                
                    a = 0
                    for i in y:
                        if i == "0":
                            a = a + 1
                        elif i == "1":
                            return y[a:100]
            Recommended code:
            Code:
                    return y.lstrip('0')

            There is nothing wrong with string concatenation. I prefer string formatting for efficiency and readability.
            Original code:
            Code:
            print "Your number, " + str(inp) + ", is " + dec2bi(int(inp)) + " in binary!"
            Recommended code:
            Code:
            print "Your number, %s, is %s in binary" % (inp, dec2bi(int(inp))

            Comment

            • MorseCode
              New Member
              • Dec 2008
              • 3

              #7
              Thanks for the help, bv, you taught me (a fairly new newb) a few things I didn't know.
              Namely, everything you showed me in your post. Lol.

              Comment

              • bvdet
                Recognized Expert Specialist
                • Oct 2006
                • 2851

                #8
                You're welcome MorseCode. Following is a function that will convert a decimal number to any base between and including 2-36. It uses built-in function divmod() and recursion.
                Code:
                def convDecToBase(num, base, dd=False):
                    ''' Convert a decimal integer to a base between and including 2-36.'''
                    if not 2 <= base <= 36:
                        raise ValueError, 'The base number must be between 2 and 36.'
                    if not dd:
                        dd = dict(zip(range(36), list(string.digits+string.ascii_lowercase)))
                    if num == 0: return ''
                    num, rem = divmod(num, base)
                    return convDecToBase(num, base, dd)+dd[rem]

                Comment

                Working...