Bit.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. using System;
  2. using System.Collections;
  3. namespace S7.Net.Types
  4. {
  5. /// <summary>
  6. /// Contains the conversion methods to convert Bit from S7 plc to C#.
  7. /// </summary>
  8. public static class Bit
  9. {
  10. /// <summary>
  11. /// Converts a Bit to bool
  12. /// </summary>
  13. public static bool FromByte(byte v, byte bitAdr)
  14. {
  15. return (((int)v & (1 << bitAdr)) != 0);
  16. }
  17. /// <summary>
  18. /// Converts an array of bytes to a BitArray.
  19. /// </summary>
  20. /// <param name="bytes">The bytes to convert.</param>
  21. /// <returns>A BitArray with the same number of bits and equal values as <paramref name="bytes"/>.</returns>
  22. public static BitArray ToBitArray(byte[] bytes) => ToBitArray(bytes, bytes.Length * 8);
  23. /// <summary>
  24. /// Converts an array of bytes to a BitArray.
  25. /// </summary>
  26. /// <param name="bytes">The bytes to convert.</param>
  27. /// <param name="length">The number of bits to return.</param>
  28. /// <returns>A BitArray with <paramref name="length"/> bits.</returns>
  29. public static BitArray ToBitArray(byte[] bytes, int length)
  30. {
  31. if (length > bytes.Length * 8) throw new ArgumentException($"Not enough data in bytes to return {length} bits.", nameof(bytes));
  32. var bitArr = new BitArray(bytes);
  33. var bools = new bool[length];
  34. for (var i = 0; i < length; i++) bools[i] = bitArr[i];
  35. return new BitArray(bools);
  36. }
  37. }
  38. }