# Node-red-contrib-mcp23017chip

**URL:** <https://discourse.nodered.org/t/node-red-contrib-mcp23017chip/37999>\
**Category:** General\
**Created:** [25 December 2020 08:30 UTC](https://discourse.nodered.org/t/node-red-contrib-mcp23017chip/37999 "2020-12-25T08:30:32Z")\
**Posts on this page:** 1\
**Showing post:** 71

<div class="post-metadata">

**Author:** ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)\
**Post date:** [5 January 2021 09:36 UTC](https://discourse.nodered.org/t/node-red-contrib-mcp23017chip/37999/71 "2021-01-05T09:36:56Z")

</div>

I tend to use a set of functions that help me avoid typos...

```auto
//Get bit
function getBit(number, bitPosition) {
  return (number & (1 << bitPosition)) === 0 ? 0 : 1;
}

//Set Bit
function setBit(number, bitPosition) {
  return number | (1 << bitPosition);
}

//Clear Bit
function clearBit(number, bitPosition) {
  const mask = ~(1 << bitPosition);
  return number & mask;
}

//Update Bit
function updateBit(number, bitPosition, bitValue) {
  const bitValueNormalized = bitValue ? 1 : 0;
  const clearMask = ~(1 << bitPosition);
  return (number & clearMask) | (bitValueNormalized << bitPosition);
}

```

e.g...

```auto
let readVal = 0, writeVal = 0;
let writeByte = 0x14, readByte = 0x12, bit = bitNum;
if (bitNum >= 8) {
    writeByte = 0x15;
    readByte = 0x13
    bit = bitNum - 8;
}

readVal = _aBus.readByteSync(_addr, readByte); //read the value
writeVal = updateBit(readVal, bit, newState); //set/reset the bit
_aBus.writeByteSync(_addr, writeByte, writeVal & 0xFF); //write back new value

```

---

_[View the full topic](https://discourse.nodered.org/t/node-red-contrib-mcp23017chip/37999)._
