Skip to content

Commit

Permalink
Add SetBit method to modify one bit of a byte
Browse files Browse the repository at this point in the history
  • Loading branch information
Himmelt committed Aug 15, 2023
1 parent a8ef47b commit 2ec7322
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
16 changes: 16 additions & 0 deletions S7.Net.UnitTest/ConvertersUnitTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,21 @@ public void T00_TestSelectBit()
Assert.IsFalse(dummyByte.SelectBit(7));

}

[TestMethod]
public void T01_TestSetBit()
{
byte dummyByte = 0xAA; // 1010 1010
dummyByte.SetBit(0, true);
dummyByte.SetBit(1, false);
dummyByte.SetBit(2, true);
dummyByte.SetBit(3, false);
Assert.AreEqual<byte>(dummyByte, 0xA5);// 1010 0101
dummyByte.SetBit(4, true);
dummyByte.SetBit(5, true);
dummyByte.SetBit(6, true);
dummyByte.SetBit(7, true);
Assert.AreEqual<byte>(dummyByte, 0xF5);// 1111 0101
}
}
}
45 changes: 45 additions & 0 deletions S7.Net/Conversion.cs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,51 @@ public static bool SelectBit(this byte data, int bitPosition)
return (result != 0);
}

/// <summary>
/// Helper to set a bit value to the given byte at the bit index.
/// </summary>
/// <param name="data"></param>
/// <param name="bitPosition"></param>
/// <param name="value"></param>
public static void SetBit(this ref byte data, int bitPosition, bool value)
{
if (bitPosition < 0 || bitPosition > 7)
{
return;
}

if (value)
{
switch (bitPosition)
{
case 0: data |= 0x01; return;
case 1: data |= 0x02; return;
case 2: data |= 0x04; return;
case 3: data |= 0x08; return;
case 4: data |= 0x10; return;
case 5: data |= 0x20; return;
case 6: data |= 0x40; return;
case 7: data |= 0x80; return;
default: return;
}
}
else
{
switch (bitPosition)
{
case 0: data &= 0xFE; return;
case 1: data &= 0xFD; return;
case 2: data &= 0xFB; return;
case 3: data &= 0xF7; return;
case 4: data &= 0xEF; return;
case 5: data &= 0xDF; return;
case 6: data &= 0xBF; return;
case 7: data &= 0x7F; return;
default: return;
}
}
}

/// <summary>
/// Converts from ushort value to short value; it's used to retrieve negative values from words
/// </summary>
Expand Down

0 comments on commit 2ec7322

Please sign in to comment.