Convert a sequence of bits to a bit-string

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Dec 15 10:48:53 EST 2007


On Sat, 15 Dec 2007 14:33:04 +0000, te509 wrote:

> Hi guys,
> does anybody know how to convert a long sequence of bits to a
> bit-string? 

Can you explain what you actually mean?

For instance... 

x = 1234567890

x is now a long sequence of bits.


> I want to avoid this:
> 
>>>> 
bit=0011010000000000000111111111111111000000000000000001111111010111111111111001
>>>> str(bit)
> '949456129574336313917039111707606368434510426593532217946399871489'

Rather than telling us what you DON'T want, perhaps you should tell us 
what you DO want.

Also, bit (singular) is a bad name for something which is obviously many 
bits (plural).

00110... [many digits skipped] is a very large number written in octal 
(base 8). It contains 220 bits, regardless of whether you print them in 
base 2, base 8, base 10 or base 256.



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

Thank you for your honesty.

You should think more carefully about what you are trying to accomplish. 
Is your input a string of 0 and 1 characters, or a binary sequence of 
bits? What is your output?

e.g. bits = '010011001' # a sequence of characters representing bits
bits = 987654 # bits specified in base 10

(2) Python has built-in functions oct() hex() str() and int(). You may 
like to Read The Fine Manual using the built-in help.

e.g. help(oct)
Help on built-in function oct in module __builtin__:

oct(...)
    oct(number) -> string

    Return the octal representation of an integer or long integer.



(3) Once you've explained what you're trying to do, think more carefully 
about how to accomplish it.

e.g. the decimal string '123' is equal to 1*10**2 + 2*10**1 + 3*10**0.
the octal string '406' is equal to 4*8**2 + 0*8**1 + 6*8**0
the binary string '101' is equal to ... ?


(4) You might also like to consider the words "convert from one base to 
another" as worthy of further research.


Good luck on your assignment. Don't forget to quote your sources, 
including any code snippets you find on the web.



-- 
Steven



More information about the Python-list mailing list