read string in bits

John Machin sjmachin at lexicon.net
Wed Jan 14 03:33:49 EST 2009


On Jan 14, 6:44 pm, ts <thaisi... at gmail.com> wrote:
> On Jan 14, 3:32 pm, Chris Rebert <c... at rebertia.com> wrote:
>
>
>
> > On Tue, Jan 13, 2009 at 11:21 PM, ts <thaisi... at gmail.com> wrote:
> > > hi, is there a way to read a character/string into bits in python?
>
> > > i understand that character is read in bytes. Do i have to write a
> > > function to convert it myself into 1010101 or there is a library in
> > > python that enable me to do that?
>
> > It's not quite clear to me what you mean, but here are 2 guesses:
> > - If you want to convert an ASCII character to its ASCII integer
> > value, use ord()
> > - If you want to convert an integer into a string of its base-2
> > representation, use bin() [requires Python 2.6, I think]
>
> > Cheers,
> > Chris
>
> > --
> > Follow the path of the Iguana...http://rebertia.com
>
> hi, bin() is what i'm looking for. But only python 2.4 is available to
> me. Is there a replacement of bin() in python 2.4?

No. You would have to write some code 8-(
This should give you some clues:

| Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit
(Intel)] on win32
| Type "help", "copyright", "credits" or "license" for more
information.
| >>> def char_as_number(char, base):
| ...     assert 2 <= base <= 16
| ...     n = ord(char)
| ...     if not n:
| ...         return '0'
| ...     result = ''
| ...     while n:
| ...         n, r = divmod(n, base)
| ...         result = '0123456789ABCDEF'[r] + result
| ...     return result
| ...
| >>> [char_as_number(chr(x), 2) for x in (0, 1, 7, 8, 127, 128, 255)]
| ['0', '1', '111', '1000', '1111111', '10000000', '11111111']
| >>> [char_as_number(chr(x), 2).zfill(8) for x in (0, 1, 7, 8, 127,
128, 255)]
| ['00000000', '00000001', '00000111', '00001000', '01111111',
'10000000', '11111111']
| >>> [char_as_number(chr(x), 16).zfill(2) for x in (0, 1, 7, 8, 127,
128, 255)]
| ['00', '01', '07', '08', '7F', '80', 'FF']
| >>> [char_as_number(chr(x), 8).zfill(3) for x in (0, 1, 7, 8, 127,
128, 255)]
| ['000', '001', '007', '010', '177', '200', '377']
| >>>

HTH,
John



More information about the Python-list mailing list