[Tutor] Conversion question

Wayne srilyk at gmail.com
Tue Jun 16 21:37:56 CEST 2009


On Tue, Jun 16, 2009 at 2:25 PM, Tom Green <xchimeras at gmail.com> wrote:

> Correct 8-bit ASCII.  Sorry about that.  I am using Python 2.5.2, which
> doesn't support bin.  If I upgraded how would I go about converting the
> entire string to 8-bit ASCII?
>
> I appreciate your help.


 you write the conversion yourself.




   1. # convert a decimal (denary, base 10) integer to a binary string (base 2)
   2. # tested with Python24   vegaseat    6/1/2005
   3.
   4. def Denary2Binary(n):
   5.     '''convert denary integer n to binary string bStr'''
   6.
       bStr = ''
   7.     if n < 0:  raise ValueError, "must be a positive integer"
   8.     if n == 0: return '0'
   9.     while n > 0:
   10.         bStr = str(n % 2) + bStr
   11.         n = n >> 1
   12.     return bStr
   13.
   14. def int2bin(n, count=24):
   15.     """returns the binary of integer n, using count number of digits"""
   16.     return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)])
   17.
   18. # this test runs when used as a standalone program, but not as
an imported module
   19. # let's say you save this module as den2bin.py and use it in
another program
   20. # when you import den2bin the __name__ namespace would now be
den2bin  and the
   21. # test would be ignored
   22. if __name__ == '__main__':
   23.     print Denary2Binary(255)  # 11111111
   24.
   25.     # convert back to test it
   26.     print int(Denary2Binary(255), 2)  # 255
   27.
   28.     print
   29.
   30.     # this version formats the binary
   31.     print int2bin(255, 12)  # 000011111111
   32.     # test it
   33.     print int("000011111111", 2)  # 255
   34.
   35.     print
   36.
   37.     # check the exceptions
   38.     print Denary2Binary(0)
   39.     print Denary2Binary(-5)  # should give a ValueError

from http://www.daniweb.com/code/snippet285.html#

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090616/98c9e9ff/attachment-0001.htm>


More information about the Tutor mailing list