Last Updated: February 25, 2016
·
1.096K
· chauvd

Converting Alpha to Binary and Vice-Versa

Binary conversion and manipulation is not used as often, especially with base64 supported functions in python. You can use bin() functionality supported in python > 2.6 to convert between ASCII representation.

def a2b(string):
    result = ''

    for i in xrange(0,len(string)):
        temp = bin(ord(string[i]))[2:].zfill(chunkSize)
        result += temp

    return result

The conversion will zfill the length of the binary representation to an appropriate chunk size (depending on the transfer buffer size when sending data). Conversely the translation back to ASCII is as follows;

def b2a(data):
    result = ''
    base   = 2
    i      = 0

    while i < len(data):
        chunk = data[i:i+chunkSize]
        n = int(chunk,base)
        result += chr(n)
        i += chunkSize

    return result

This runs through each 8 bit chunk to convert the binary string into an int via int(x,2), where 2 is the base for conversion and x is the binary string. Each chunk is 8 bit for obvious reasons regarding character representation in ASCII. Again, the chunk size used to convert the data needs to be known.