| | |
Decimal to Binary Conversion (Python)
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Converting a decimal integer (denary, base 10) to a binary string (base 2) is amazingly simple. An exception is raised for negative numbers and zero is a special case. To test the result, the binary string is converted back to the decimal value, easily done with the int(bStr, 2) function.
# convert a decimal (denary, base 10) integer to a binary string (base 2) # tested with Python24 vegaseat 6/1/2005 def Denary2Binary(n): '''convert denary integer n to binary string bStr''' bStr = '' if n < 0: raise ValueError, "must be a positive integer" if n == 0: return '0' while n > 0: bStr = str(n % 2) + bStr n = n >> 1 return bStr def int2bin(n, count=24): """returns the binary of integer n, using count number of digits""" return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)]) # this test runs when used as a standalone program, but not as an imported module # let's say you save this module as den2bin.py and use it in another program # when you import den2bin the __name__ namespace would now be den2bin and the # test would be ignored if __name__ == '__main__': print Denary2Binary(255) # 11111111 # convert back to test it print int(Denary2Binary(255), 2) # 255 # this version formats the binary print int2bin(255, 12) # 000011111111 # test it print int("000011111111", 2) # 255 # check the exceptions print Denary2Binary(0) print Denary2Binary(-5) # should give a ValueError
Similar Threads
- Code Snippet: Decimal to Binary conversion (C)
- Code Snippet: Binary to Decimal Conversion (C)
- Help With Decimal to Binary conversion (IT Professionals' Lounge)
- decimal to binary conversion (C++)
- Help! Decimal to binary conversion (C)
| Thread Tools | Search this Thread |
Tag cloud for Python
abrupt apache application argv beginner binary calculator character code command cursor cx-freeze development dictionary dynamic error event examples excel file float format ftp function google gui hints homework ideas import input java keyboard launcher line linux list lists loop microphone mouse movingimageswithpygame newb number numbers obexftp output parsing path permissions phonebook port prime program programming projects py2exe pygame pyglet pyqt pysimplewizard python random recursion recursive refresh return reverse scrolledtext session shebang signal simple sprite ssh string strings table terminal text thread threading time tkinter tlapse trick tuple tutorial ubuntu unicode unit urllib urllib2 valueerror variable verify voip windows wordgame wxpython



