Ascii to binary conversion

Mensanator mensanator at
Sat Aug 9 16:49:46 CEST 2008

On Aug 9, 8:18�am, azrael <jura.gro... at> wrote:
> Hy folks,
> I googled, and searched, and can not bealive that I have not found a
> built in way to convert the easy and elegant python way a function to
> easily convert simple ascii data to binary and back.
> I've written some my own but they were pretty slow using binascii
> linbrary with hexifly and unhexifly functions conbined with a
> lookuptable of binary and hex values.
> Any idea how to easily write a function that recieves a character or
> string and returns a binary number like:
> ascii("1") is converted to bin("00110001")

In Pthon 2.6 & 3.0 there actually IS a bin() function.

IDLE 2.6b1
>>> bin(ord('1'))

But it has that worthless '0b' decorator, but that's
easily dealt with.

>>> bin(ord('1'))[2:]

And you won't get leading 0s unless you ask for them.

>>> bin(ord('1'))[2:].zfill(8)

If you have previous Python versions (and even if you
have 2.6), you might consider getting the gmpy module.
It will convert to any base from 2 to 36 and in addition,
provides a nice set of binary manipulation functions
such as popcount (number of 1-bits), scan1 (finds posistion
of first 1-bit), Hamming Distance (number of differing
bits between two numbers), etc.

>>> import gmpy

>>> gmpy.digits(ord('1'))    # base 10 by default

>>> gmpy.digits(ord('1'),2)  # same in base 2 (note - no decorator)

>>> gmpy.digits(ord('1'),2).zfill(8) # add leading 0s

>>> gmpy.popcount(ord('1')) # of 1-bits

>>> gmpy.scan1(ord('1')) # the first 1 is at bit 0

>>> gmpy.scan1(ord('1'),1) # the next 1 is at bit 4

>>> gmpy.hamdist(ord('1'),ord('6')) # differ at 3 bit positions

And you probably won't find anything faster than gmpy.

More information about the Python-list mailing list