Manipulating specific bits

Michael Hudson mwh21 at cam.ac.uk
Thu Jun 22 06:31:56 EDT 2000


"Stephen Hansen" <stephen at cerebralmaelstrom.com> writes:

>     Okay, this is a Very Newbie-ish question.
> 
>     What I need to do is manipulate specific bits in a byte, for
> transmission. I have absolutely *no* idea how to do this. :)
>     For example, say I have my 1 byte: 0 0 0 0 0 0 0 0. Say I want to set
> the 2nd and 5th bit to 1.. how the heck do I do that? :)

byte = 0
byte = byte | (1<<4) | (1<<1)

and so on...

>     I've never actually even /blinked/ in the direction of bit-ish
> manipulation, so am utterly clueless. Next i'm gonna have to stick it into a
> struct I think, before transmission.. I think. dunno. Will look into that
> afterwards.

bitfiddling is emphatically not what Python was designed for; it's
possible, but it ain't pleasant.  Thomas Wouters's augmented
assignment patch would make it more bearable.

It's also dog slow compared to C.  This may or may not be relavent...

Cheers,
M.

-- 
  This is an off-the-top-of-the-head-and-not-quite-sober suggestion,
  so is probably technically laughable.  I'll see how embarassed I
  feel tomorrow morning.            -- Patrick Gosling, ucam.comp.misc



More information about the Python-list mailing list