1

所以我对并行端口很陌生,我一直在这里研究这段代码->> http://pyserial.svn.sourceforge.net/viewvc/pyserial/trunk/pyparallel/examples/lcd.py?revision=49&view =标记

我对这里发生的事情感到困惑

def reveseout(self, x):
    r = ((x & (1<<0) and 1) << 7) |\
        ((x & (1<<1) and 1) << 6) |\
        ((x & (1<<2) and 1) << 5) |\
        ((x & (1<<3) and 1) << 4) |\
        ((x & (1<<4) and 1) << 3) |\
        ((x & (1<<5) and 1) << 2) |\
        ((x & (1<<6) and 1) << 1) |\
        ((x & (1<<7) and 1) << 0)
    #print "%02x" % r, "%02x" %x
    self.p.setData(r)

我知道这是反转引脚,但我不理解语法本身以及它的字面意思。
任何帮助将不胜感激谢谢!

4

1 回答 1

6

Let's take it piece by piece: 1<<n is a 1 shifted n places to the left, so these values give us 0x01, 0x02, 0x04, 0x08, 0x10, etc, the bits in a byte. x & (1<<n) is x masked with that bit, so we get the individual bits of x. x & (1<<n) and 1 is tricky: if the bit is set in x, then it will evaluate as the second argument, and it will be 1. If the bit is not set in x, then it will be zero. So x & (1<<n) and 1 is 1 if the bit is set in x, 0 if not.

(x & (1<<n) and 1) << m takes that zero or one and shifts it to the left m places, so it essentially copies the n'th bit and puts it in the m'th bit. The eight lines use 0 and 7 for n and m, then 1 and 6, then 2 and 5, etc, so we get eight values. The first is the 0th bit in the 7th place, then the 1th bit in the 6th place and so on. Finally, they are all or'ed together with | to build a single byte with the bits reversed.

于 2012-07-10T02:49:27.507 回答