user1161439
user1161439

Reputation: 141

pyParallel python swapping pins

So I'm pretty new with parallel ports and I've been studying this code here ->> http://pyserial.svn.sourceforge.net/viewvc/pyserial/trunk/pyparallel/examples/lcd.py?revision=49&view=markup

and I am confused as to what is going on here

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)

I understand it's to reverse pins, but I don't understand the syntax itself and what it's literally saying.
Any help would be greatly appreciated Thanks!

Upvotes: 1

Views: 376

Answers (1)

Ned Batchelder
Ned Batchelder

Reputation: 375604

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.

Upvotes: 6

Related Questions