Convert a sequence of bits to a bit-string

mensanator at aol.com mensanator at aol.com
Sat Dec 15 10:56:42 EST 2007


On Dec 15, 8:33�am, te... at york.ac.uk wrote:
> Hi guys,
> does anybody know how to convert a long
> sequence of bits to a bit-string? I want to avoid this:
>
> >>> bit=00110100000000000001111111111111110000000000000000011111110101111111111�11001
> >>> str(bit)
>
> '949456129574336313917039111707606368434510426593532217946399871489'

That's not a sequence of bits, it's a sequence of
octal digits (because you started with a leading 0).

There is no base 2 numeric format in Python.

You can enter strings reprsenting base 2 digits
and then convert the string to an integer:

>>> bit='0011010000000000000111111111111111000000000000000001111111010111111111111001'
>>> bit_as_base2 = int(bit,2)

Where you'll see what the correct decimal is:

>>> bit_as_base2
15347835180116409679865L

As I said, the number you entered was actually octal.
Watch as I convert the string to base 8:

>>> bit_as_base8=int(bit,8)
>>> bit_as_base8
949456129574336313917039111707606368434510426593532217946399871489L

See, I got your original number.

You could change your original pattern from octal
to binary by substituting '000' for each '0' and
'001' for each '1'. This works because both octal
and binary are powers of 2.

>>> bit2=re.sub('0','000',bit)
>>> bit2=re.sub('1','001',bit2)
>>> bit2
'000000001001000001000000000000000000000000000000000000000001001001001001001001001001001001001001001001000000000000000000000000000000000000000000000000000001001001001001001001000001000001001001001001001001001001001001001000000001'

This string, when interpreted as base 2 gives
you the same result as the original number
interpreted as base 8.

>>> bit2_as_base2=int(bit2,2)
>>> bit2_as_base2
949456129574336313917039111707606368434510426593532217946399871489L

If you really need full base 2 capability in place
of the halfway capability of Python, get the gmpy
module:

>>> import gmpy
>>> for x in xrange(16):
         # convert int to base2 and pad
         # to a fixed number of bits
	print gmpy.digits(x,2).zfill(8)


00000000
00000001
00000010
00000011
00000100
00000101
00000110
00000111
00001000
00001001
00001010
00001011
00001100
00001101
00001110
00001111



>
> I would appreciate a prompt reply because I have a python assessment to
> submit.
> Thanks,
> Thomas




More information about the Python-list mailing list