Add ToBitArray overload with length

This commit is contained in:
Michael Croes
2018-07-11 22:30:10 +02:00
parent 4fcab9a167
commit b3cb45de37

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);
}
}
}