Manipulating specific bits

John Parkey jparkey at nospamrapidbs.com
Thu Jun 22 07:29:57 EDT 2000


Stephen

You can use the bit-wise manipulation, using masks to set and clear bits
(Mike's example dynamically sets up a mask).
To set the fifth and second bits, you need to 'OR' your byte with a mask
which has those bits set.

The mask would be:  00010010 in binary, = 12Hex (0x12) = 22Octal (022), so
you would set the two bits by saying:

byte = byte | 0x12.

To check whether a bit is set, you need to 'AND' it with a mask representing
the bit.  So, to test if bit 3 is set, the mask needed is:  00000100 in
binary, = 0x4(Hex) = 04(Octal), and you can check whether your byte has it
set by saying:

result = byte & 0x4.

To clear a bit, you need a bit mask which is a complement of the bit(s) you
are testing for, which you AND with your test byte.

For example, to clear bit 3, you need to AND with: 11111011 in binary, =
0xFB(hex) =  0373(Octal), so you would say:

result = byte & 0xFB.

To save you having to work out the complement, you can use the '~' symbol,
for bitwise inversion.  So, to clear bit 2, you just need to say:

byte = byte & ~0x04

"Michael Hudson" <mwh21 at cam.ac.uk> wrote in message
news:m3snu63t2b.fsf at atrus.jesus.cam.ac.uk...
> "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)
>






More information about the Python-list mailing list