Efficient Bit addressing in Python.

Ross Ridge rridge at csclub.uwaterloo.ca
Sat Oct 11 22:20:35 EDT 2008


Ross Ridge  wrote:
>I don't think you can do anything faster with standard modules, although
>it might not be efficient if you're only working with a single byte.

Hendrik van Rooyen <mail at microcorp.co.za> wrote:
>Thanks I was not aware of binascii module this looks powerful.

Not really.  It's just used as part of a trick to quickly convert a byte
string in to a bit string (a byte string with just 0s and 1s).

Unfortunately fromr you other posts you do seem to be working on
a single byte a time, so my technique probably won't be efficient.
You probably want just want to be using constants and bit masking.
Something like:

	
	PAC_EMERGENCY_STOP   = 0x01  # bit #0 on output port 0
	PAC_OUTPUT_0_1	     = 0x02  # replace with names for other functions
	PAC_OUTPUT_0_2	     = 0x04
	PAC_PNEUMATIC_PUSHER = 0x08  # bit #3 on output port 0
	...

	def gpio_bit_on(port, bit):
		r = gpio_in(port)
		r |= bit
		r = gpio_out(port)
		
	def gpio_bit_off(port, bit):
		r = gpio_in(port)
		r &= ~bit
		r = gpio_out(port)
		
	class pac(object):
		def everything_off(self):
			gpio_out(PAC_OUTPUT_PORT_0, 0)
			gpio_out(PAC_OUTPUT_PORT_1, 0)
			gpio_out(PAC_OUTPUT_PORT_2, 0)
			...
			gpio_out(PAC_OUTPUT_PORT_7, 0)

		def emergency_stop(self):
			gpio_bit_on(PAC_OUTPUT_PORT_0, PAC_EMERGENCY_STOP)

		def pusher_on(self):
			gpio_bit_on(PAC_OUTPUT_PORT_0, PAC_PNEUMATIC_PUSHER)

		def pusher_off(self):
			gpio_bit_off(PAC_OUTPUT_PORT_0, PAC_PNEUMATIC_PUSHER)


Bit twiddling like this is pretty basic.

				Ross Ridge

-- 
 l/  //	  Ross Ridge -- The Great HTMU
[oo][oo]  rridge at csclub.uwaterloo.ca
-()-/()/  http://www.csclub.uwaterloo.ca/~rridge/ 
 db  //	  



More information about the Python-list mailing list