String.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. namespace S7.Net.Types
  2. {
  3. /// <summary>
  4. /// Contains the methods to convert from S7 Array of Chars (like a const char[N] C-String) to C# strings
  5. /// </summary>
  6. public class String
  7. {
  8. /// <summary>
  9. /// Converts a string to <paramref name="reservedLength"/> of bytes, padded with 0-bytes if required.
  10. /// </summary>
  11. /// <param name="value">The string to write to the PLC.</param>
  12. /// <param name="reservedLength">The amount of bytes reserved for the <paramref name="value"/> in the PLC.</param>
  13. public static byte[] ToByteArray(string value, int reservedLength)
  14. {
  15. var bytes = new byte[reservedLength];
  16. if (value == null) return bytes;
  17. var length = value.Length;
  18. if (length == 0) return bytes;
  19. if (length > reservedLength) length = reservedLength;
  20. System.Text.Encoding.ASCII.GetBytes(value, 0, length, bytes, 0);
  21. return bytes;
  22. }
  23. /// <summary>
  24. /// Converts S7 bytes to a string
  25. /// </summary>
  26. /// <param name="bytes"></param>
  27. /// <returns></returns>
  28. public static string FromByteArray(byte[] bytes)
  29. {
  30. return System.Text.Encoding.ASCII.GetString(bytes);
  31. }
  32. }
  33. }