binary string question

Alexander Schmolck a.schmolck at gmx.net
Sat Nov 8 00:32:30 CET 2003


Dan Jones <djones at shcorp.com> writes:

> Hello,
> 
> I'm trying to figure out how to get bit operators to work on a binary
> string. 

More below, but are you sure you really need to do this?

> This is what I'm trying to do:
> 
> list(frame) #where frame is a binary string

This has no effect (apart from wasting ressources). You create a new list from
the string frame, but don't use it any further. You presumably intended

  frame = list(frame)

> y = frame[x] << 8
> 
> It gives me a TypeError. Whats the best way to get around that? 

Well see below (not that I can see how rightshifting by 8 is going to make
much sense if you want to treat a string as collection of bytes).

> I think the struct module may be what I'm looking for, 

You want to treat each item in the string the same, right? In that case use
array.

> if so could someone give me an example?

Here you go:

>>> import array
>>> frame = "abcde"
>>> frameAsArray = array.array('b', frame)
>>> frameAsArray[0] >>= 1
>>> frameAsArray.tostring()
'0bcde'

> Also, is there a better way to be able to access individual bytes than
> converting the string to a list?

see above

'as




More information about the Python-list mailing list