diff --git a/S7.Net/PLCHelpers.cs b/S7.Net/PLCHelpers.cs index 803d349..2ea37cd 100644 --- a/S7.Net/PLCHelpers.cs +++ b/S7.Net/PLCHelpers.cs @@ -145,7 +145,7 @@ namespace S7.Net } else { - return Bit.ToBitArray(bytes); + return Bit.ToBitArray(bytes, varCount); } case VarType.DateTime: if (varCount == 1) @@ -172,7 +172,7 @@ namespace S7.Net switch (varType) { case VarType.Bit: - return varCount; //TODO + return varCount + 7 / 8; case VarType.Byte: return (varCount < 1) ? 1 : varCount; case VarType.String: diff --git a/S7.Net/Types/Bit.cs b/S7.Net/Types/Bit.cs index 5f00476..5214fd9 100644 --- a/S7.Net/Types/Bit.cs +++ b/S7.Net/Types/Bit.cs @@ -1,4 +1,5 @@ -using System.Collections; +using System; +using System.Collections; namespace S7.Net.Types { @@ -16,12 +17,27 @@ namespace S7.Net.Types } /// - /// Converts an array of bytes to a BitArray + /// Converts an array of bytes to a BitArray. /// - public static BitArray ToBitArray(byte[] bytes) + /// The bytes to convert. + /// A BitArray with the same number of bits and equal values as . + public static BitArray ToBitArray(byte[] bytes) => ToBitArray(bytes, bytes.Length * 8); + + /// + /// Converts an array of bytes to a BitArray. + /// + /// The bytes to convert. + /// The number of bits to return. + /// A BitArray with bits. + public static BitArray ToBitArray(byte[] bytes, int length) { - BitArray bitArr = new BitArray(bytes); - return bitArr; + if (length > bytes.Length * 8) throw new ArgumentException($"Not enough data in bytes to return {length} bits.", nameof(bytes)); + + var bitArr = new BitArray(bytes); + var bools = new bool[length]; + for (var i = 0; i < length; i++) bools[i] = bitArr[i]; + + return new BitArray(bools); } } }