Merge pull request #167 from mycroes/bit-arrays

Fix incorrect length when reading BitArray
This commit is contained in:
Michael Croes
2019-07-17 21:50:12 +02:00
committed by GitHub
2 changed files with 23 additions and 7 deletions

View File

@@ -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:

View File

@@ -1,4 +1,5 @@
using System.Collections;
using System;
using System.Collections;
namespace S7.Net.Types
{
@@ -16,12 +17,27 @@ namespace S7.Net.Types
}
/// <summary>
/// Converts an array of bytes to a BitArray
/// Converts an array of bytes to a BitArray.
/// </summary>
public static BitArray ToBitArray(byte[] bytes)
/// <param name="bytes">The bytes to convert.</param>
/// <returns>A BitArray with the same number of bits and equal values as <paramref name="bytes"/>.</returns>
public static BitArray ToBitArray(byte[] bytes) => ToBitArray(bytes, bytes.Length * 8);
/// <summary>
/// Converts an array of bytes to a BitArray.
/// </summary>
/// <param name="bytes">The bytes to convert.</param>
/// <param name="length">The number of bits to return.</param>
/// <returns>A BitArray with <paramref name="length"/> bits.</returns>
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);
}
}
}