# Setting Bit 15 of a Short not working

**URL:** <https://forum.inductiveautomation.com/t/setting-bit-15-of-a-short-not-working/11968>\
**Category:** Ignition\
**Created:** [July 25, 2016, 7:16pm UTC](https://forum.inductiveautomation.com/t/setting-bit-15-of-a-short-not-working/11968 "2016-07-25T19:16:26Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Weffrey](https://avatars.discourse-cdn.com/v4/letter/w/6a8cbe/32.png) [@Weffrey](https://forum.inductiveautomation.com/u/Weffrey)\
**Post date:** [July 25, 2016, 7:16pm UTC](https://forum.inductiveautomation.com/t/setting-bit-15-of-a-short-not-working/11968/1 "2016-07-25T19:16:26Z")

</div>

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:

```auto
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:

```auto
	#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!

---

<div class="post-metadata">

**Author:** ![jdfrankston](https://avatars.discourse-cdn.com/v4/letter/j/f07891/32.png) [@jdfrankston](https://forum.inductiveautomation.com/u/jdfrankston)\
**Post date:** [August 9, 2016, 4:46pm UTC](https://forum.inductiveautomation.com/t/setting-bit-15-of-a-short-not-working/11968/2 "2016-08-09T16:46:47Z")

</div>

If you drop the following code in a python interpreter ([mathcs.holycross.edu/~kwalsh/python/](http://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.

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

print setBit(X,N,1)
```
