question about binary and serial info

mensanator at aol.com mensanator at aol.com
Thu Aug 18 08:01:18 CEST 2005


nephish at xit.net wrote:
> yeah, i think i got that down, i need help with getting the hex to
> binary, then splitting the byte up to compare each bit against the bit
> in another byte.

The & operator does all 8 comparisons simultaneously. So if
the serial port byte is A, the reference byte is B then

AB = A & B

has only 1 bits where both A and B had 1's in their respective
positions. Now, you can test AB for a particular bit position
(say bit 3) by

testbit3 = AB & 2**3

If testbit3 > 0 then the bit was a 1.

> unless i am not understanding this stuff with the bitwise right. there
> wasn't a lot in the python library reference about it.

The GMPY module has some interesting bit functions.

Popcount can tell you how many of the AB bits are 1 without
specifying which ones:

>>> for i in range(16):
	print gmpy.popcount(i),

0 1 1 2 1 2 2 3 1 2 2 3 2 3 3 4

Hamming distance tells you how many bits differ between
two numbers (again, without telling you which ones)

>>> for i in range(16):
	print gmpy.hamdist(i,7),

3 2 2 1 2 1 1 0 4 3 3 2 3 2 2 1

If one operand is 0, then Hamming distance is the same
as popcount.

And then there's scan1 which will tell you the bit
bit position of the first 1 bit.

>>> A = 48
>>> B = 255
>>> AB = A & B
>>> print gmpy.scan1(AB)
4

So the first 1 bit is bit 4, which means bits 0, 1, 2 and 3
are all 0.

> thanks




More information about the Python-list mailing list