diff --git a/S7.Net.UnitTest/ConvertersUnitTest.cs b/S7.Net.UnitTest/ConvertersUnitTest.cs index abbe4ac4..e14fbab0 100644 --- a/S7.Net.UnitTest/ConvertersUnitTest.cs +++ b/S7.Net.UnitTest/ConvertersUnitTest.cs @@ -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(dummyByte, 0xA5);// 1010 0101 + dummyByte.SetBit(4, true); + dummyByte.SetBit(5, true); + dummyByte.SetBit(6, true); + dummyByte.SetBit(7, true); + Assert.AreEqual(dummyByte, 0xF5);// 1111 0101 + } } } diff --git a/S7.Net/Conversion.cs b/S7.Net/Conversion.cs index 44f9e254..b389332f 100644 --- a/S7.Net/Conversion.cs +++ b/S7.Net/Conversion.cs @@ -138,19 +138,59 @@ public static string ValToBinString(this object value) /// /// 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); + ///
+ /// + /// Get the bit at DB1.DBX0.5: + /// + /// byte data = ReadByte("DB1.DBB0"); + /// bool bit = data.SelectBit(5); + /// + /// ///
- /// - /// - /// - public static bool SelectBit(this byte data, int bitPosition) + /// The data to get from. + /// The zero-based index of the bit to get. + /// The Boolean value will get. + public static bool SelectBit(this byte data, int index) { - int mask = 1 << bitPosition; + int mask = 1 << index; int result = data & mask; return (result != 0); } + /// + /// Helper to set a bit value to the given byte at the bit index. + ///
+ /// + /// Set the bit at index 4: + /// + /// byte data = 0; + /// data.SetBit(4, true); + /// + /// + ///
+ /// The data to be modified. + /// The zero-based index of the bit to set. + /// The Boolean value to assign to the bit. + 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; + } + } + /// /// Converts from ushort value to short value; it's used to retrieve negative values from words ///