Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add SetBit method to modify one bit of a byte #501

Merged
merged 7 commits into from
Aug 18, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}
}
}
25 changes: 25 additions & 0 deletions S7.Net/Conversion.cs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,31 @@ 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>
Himmelt marked this conversation as resolved.
Show resolved Hide resolved
/// <param name="bitPosition"></param>
/// <param name="value"></param>
public static void SetBit(this ref byte data, int bitPosition, bool value)
Himmelt marked this conversation as resolved.
Show resolved Hide resolved
{
if ((uint)bitPosition > 7)
{
return;
}

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

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