From: Back9 on
Hi,

I have one byte data and want to know each bit info,
I mean how I can know each bit is set or not?

TIA
From: Tim Lesher on
On Jun 17, 3:51 pm, Back9 <backgoo...(a)gmail.com> wrote:
> Hi,
>
> I have one byte data and want to know each bit info,
> I mean how I can know each bit is set or not?

You want the bitwise-and operator, &.

For example, to check the least significant bit, bitwise-and with 1:

>>> 3 & 1
1
>>> 2 & 1
0
From: Laurent Verweijen on
Op donderdag 17-06-2010 om 12:51 uur [tijdzone -0700], schreef Back9:
> Hi,
>
> I have one byte data and want to know each bit info,
> I mean how I can know each bit is set or not?
>
> TIA

def bitset(x, n):
"""Return whether nth bit of x was set"""
return bool(x & (1 << n))

From: Irmen de Jong on
On 17-6-2010 21:51, Back9 wrote:
> Hi,
>
> I have one byte data and want to know each bit info,
> I mean how I can know each bit is set or not?
>
> TIA

Use bitwise and, for instance, to see if the third bit is set:

byte = 0b11111111
if byte & 0b00000100:
print "bit is set"

-irmen
From: Stephen Hansen on
On 6/17/10 12:51 PM, Back9 wrote:
> I have one byte data and want to know each bit info,
> I mean how I can know each bit is set or not?

>>> BIT_1 = 1 << 0
>>> BIT_2 = 1 << 1
>>> BIT_3 = 1 << 2
>>> BIT_4 = 1 << 3
>>> BIT_5 = 1 << 4
>>> BIT_6 = 1 << 5
>>> BIT_7 = 1 << 6
>>> BIT_8 = 1 << 7
>>> byte = 67
>>> if byte & BIT_1:
... print "Bit 1 is set!"
... else:
... print "Bit 1 is not set!"
Bit 1 is set!
>>> if not byte & BIT_6:
... byte = byte | BIT_6
... print "Bit 6 wasn't set, BUT NOW IS."
Bit 6 wasn't set, BUT NOW IS.
>>> byte
99

(I added 'how to set a specific bit' just cuz)

Basically, those BIT_X lines are creating numbers which have *only* the
specified bit set. Then you do "byte & BIT_X", and that will return 0 if
the byte doesn't have the specified bit in it. You can then set the bit
with "byte | BIT_X", and unset the bit with "byte ^ BIT_X".

--

Stephen Hansen
... Also: Ixokai
... Mail: me+list/python (AT) ixokai (DOT) io
... Blog: http://meh.ixokai.io/