Setting Bit 15 of a Short not working

I have been using the following routines to set bits of PLC command words, but found an problem. If the PLC word is cast as a “Short”, which corresponds to a regular word it will work on all bits but bit 15. If the target of the command is an Int setting bit 15 is fine.

Scripts in shared.bit:

def setBit(value, position, newValue):
   newValue = (newValue & 1) << position
   mask = 1 << position
   return (value & ~mask) | newValue   
   
def writeBit(tagPath, position, value):
   import system
   currentValue = system.tag.getTagValue(tagPath)
   system.tag.writeToTag(tagPath, shared.bit.setBit(currentValue, position, value))

Script is in a change script function:

	#Use Custom Routine writeBit(tagPath, position, value)
	if(currentValue.getValue() == 1):
	  shared.bit.writeBit("[.]../../../CMD/WR_HR29952",15,1) #write bit to Register Tag
	system.tag.write(tagPath, 0) #clear this tag

Again if this is used on bit 15 as shown above, the target word remains 0 (MSB of Short not set). If any other bit is set it works.

There must be something I am not seeing, as I would expect that bit 15 of the short can be set as easily as any other bit?

Thanks!

If you drop the following code in a python interpreter (mathcs.holycross.edu/~kwalsh/python/, or idle) you get (2^N)+X. In the case of the 15th bit you get 2^15+X which is at least 1 greater than the largest value you can store in 2 byte short (2^15-1). In order to get the desired results I had to use some math to convert from the 32 bit int to the 16 bit unsigned short (setBit(0,15,1) % (2**15-1).

Hope that helped.

def setBit(value, position, newValue):
   newValue = (newValue & 1) << position
   mask = 1 << position
   return (value & ~mask) | newValue   

print setBit(X,N,1)