[Tutor] Conversion question

Lie Ryan lie.1296 at gmail.com
Tue Jun 16 22:09:01 CEST 2009


Tom Green 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?
> 

AFAIK, earlier versions of python does not have a function/module that
converts a number to its binary representation; so you might have to
build your own function there.

The concept of base-2 conversion is simple, the modulus for powers of 2.

>>> def bin(n):
...     if n == 0: return '0'
...     if n == 1: return '1'
...     return mybin(n // 2) + str(n % 2)

(that function is simple, but might be slow if you had to concatenate
large strings)

or generally:
def rebase(n, base=2):
    '''
      Convert a positive integer to number string with base `base`
    '''
    if 0 <= n < base: return str(n)
    return rebase(n // base, base) + str(n % base)


than you simply map your string to ord and the bin function, ''.join,
and done.


More information about the Tutor mailing list