Skip to content

Commit

Permalink
Merge pull request #501 from Himmelt/add_set_bit
Browse files Browse the repository at this point in the history
Add SetBit method to modify one bit of a byte
  • Loading branch information
mycroes authored Aug 18, 2023
2 parents a8ef47b + e98ce00 commit 22451bc
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 6 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
}
}
}
52 changes: 46 additions & 6 deletions S7.Net/Conversion.cs
Original file line number Diff line number Diff line change
Expand Up @@ -138,19 +138,59 @@ public static string ValToBinString(this object value)

/// <summary>
/// Helper to get a bit value given a byte and the bit index.
/// Example: DB1.DBX0.5 -> var bytes = ReadBytes(DB1.DBW0); bool bit = bytes[0].SelectBit(5);
/// <br/>
/// <example>
/// Get the bit at DB1.DBX0.5:
/// <code>
/// byte data = ReadByte("DB1.DBB0");
/// bool bit = data.SelectBit(5);
/// </code>
/// </example>
/// </summary>
/// <param name="data"></param>
/// <param name="bitPosition"></param>
/// <returns></returns>
public static bool SelectBit(this byte data, int bitPosition)
/// <param name="data">The data to get from.</param>
/// <param name="index">The zero-based index of the bit to get.</param>
/// <returns>The Boolean value will get.</returns>
public static bool SelectBit(this byte data, int index)
{
int mask = 1 << bitPosition;
int mask = 1 << index;
int result = data & mask;

return (result != 0);
}

/// <summary>
/// Helper to set a bit value to the given byte at the bit index.
/// <br/>
/// <example>
/// Set the bit at index 4:
/// <code>
/// byte data = 0;
/// data.SetBit(4, true);
/// </code>
/// </example>
/// </summary>
/// <param name="data">The data to be modified.</param>
/// <param name="index">The zero-based index of the bit to set.</param>
/// <param name="value">The Boolean value to assign to the bit.</param>
public static void SetBit(this ref byte data, int index, bool value)
{
if ((uint)index > 7)
{
return;
}

if (value)
{
byte mask = (byte)(1 << index);
data |= mask;
}
else
{
byte mask = (byte)~(1 << index);
data &= mask;
}
}

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

0 comments on commit 22451bc

Please sign in to comment.