| | |
Binary-to-Decimal and vice-versa
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
# Simple functions to convert from decimal to binary and vice-versa def toBinary( decimalNumber ): quotient = 1 remainder = 0 tmpNum = decimalNumber finalNumberList = [] n = "" #e.g. take 14... while quotient != 0: remainder = decimalNumber % 2 #14 % 2 = 0 quotient = decimalNumber / 2 #14 / 2 = 7 decimalNumber = quotient # 7 % 2 = 1 and so on... finalNumberList.insert( 0, remainder ) # Used because all numbers are in a list, i.e. convert to string for num in finalNumberList: n += str( num ) return n def toDecimal( binaryNumber ): multiplier = 0 number = 0 for el in binaryNumber[ : : -1 ]: number += int( el ) * ( 2**multiplier ) multiplier += 1 return number print toDecimal( "1110" ) print toBinary( 45 )
0
•
•
•
•
Also note
Finally, see also this link.
python Syntax (Toggle Plain Text)
>>> bin(45) # python >= 3.0 '0b101101' >>> int('1110', 2) # python >= 2.5 14
0
•
•
•
•
Python Syntax (Toggle Plain Text)
>>> int('1110', 2) # python >= 2.5 14
hahh thanks for that bro. I've actually never tried it before and didn't know it existed.....weird

Last edited by masterofpuppets; Oct 20th, 2009 at 12:29 pm.
Similar Threads
- converting from binary to decimal and vice versa (C)
- How to convert Image into binary file and vice-versa (Java)
- Binary And Decimal Conversions (C)
- convert lower case letters to uppercase and vice-versa (C++)
- Converting byte value into integer and vice versa (C++)
| Thread Tools | Search this Thread |
Tag cloud for Python
advanced anydbm app bash beginner bits calling chmod cmd code data dictionary directory dynamic edit examples excel external feet file float format ftp function gui halp homework http images import info input ip itunes java keycontrol line linux list lists loan loop maintain millimeter mouse newb number numbers output panel parsing path port prime print program programming projects push py-mailer py2exe pygame pyqt python queue random recursion recursive scrolledtext smtp split ssh string strings sudokusolver table terminal text thread threading time tkinter tlapse tricks tuple tutorial ubuntu unicode update urllib urllib2 variable variables ventrilo web webservice whileloop windows wxpython xlib



