Ascii to binary conversion

Mensanator mensanator at aol.com
Sat Aug 9 10:49:46 EDT 2008


On Aug 9, 8:18�am, azrael <jura.gro... at gmail.com> 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'))
'0b110001'

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

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

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

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

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
'49'

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

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

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

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

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

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

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



More information about the Python-list mailing list