I tend to use a set of functions that help me avoid typos...
//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...
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