Referencing bits within words

Simple question. I was wondering if there is any way to reference an individual bit of a word. Basically, I have a tag defined in my OPC server as a word and I would like to monitor the individual bits to see if they change.


Most opc servers support this in the item addressing syntax. It depends on your server, but often “/x” means “give me the xth bit”… like “N7:1/1”. Check the server’s documentation.


I think I may have worded the question poorly. I’m trying to avoid making modifications to the OPC server. What I’d like to do is have a Word in an OPC server and a Tag in SQLTags referencing the nth bit of this Word. Is this possible?

Sure, bring that word into SQLTags as an OPC tag, and then make a DB tag bound to an expression using the getBit function.

I’m trying to reference the bits within a word, and need to do it in a python script. I came up with this so far:

a = 156
for i in range(0,16):
	mask = 2**i
	print 'Bit '+ str(i)+' = '+str(cmp(a&mask,0))

Is there a better way? I hope so, because this breaks on a 32 bit tag value (overflow on 2**31) and I would have to split into two words and loop twice. I must be missing something obvious. Thanks.

Yeah, I would shift the value instead of the mask:

a = 156 for i in range(0,16): shiftVal = a>>i print 'Bit '+ str(i)+' = '+str(cmp(shiftVal&1,0))

Thanks Colby, that’s much cleaner. As usual, the Zen of Python applies: “There should be one-- and preferably only one --obvious way to do it.”