Add length to String.ToByteArray(...)

This commit is contained in:
Michael Croes
2018-07-11 21:58:35 +02:00
parent bf4550655e
commit 09d323925a
2 changed files with 18 additions and 5 deletions

View File

@@ -16,7 +16,7 @@ namespace S7.Net.Protocol
if (dataItem.Value is string s)
return dataItem.VarType == VarType.StringEx
? StringEx.ToByteArray(s, dataItem.Count)
: Types.String.ToByteArray(s);
: Types.String.ToByteArray(s, dataItem.Count);
return SerializeValue(dataItem.Value);
}
@@ -56,7 +56,10 @@ namespace S7.Net.Protocol
case "Single[]":
return Types.Single.ToByteArray((float[])value);
case "String":
return Types.String.ToByteArray(value as string);
// Hack: This is backwards compatible with the old code, but functionally it's broken
// if the consumer does not pay attention to string length.
var stringVal = (string) value;
return Types.String.ToByteArray(stringVal, stringVal.Length);
default:
throw new InvalidVariableTypeException();
}

View File

@@ -6,11 +6,21 @@
public class String
{
/// <summary>
/// Converts a string to S7 bytes
/// Converts a string to <paramref name="reservedLength"/> of bytes, padded with 0-bytes if required.
/// </summary>
public static byte[] ToByteArray(string value)
/// <param name="value">The string to write to the PLC.</param>
/// <param name="reservedLength">The amount of bytes reserved for the <paramref name="value"/> in the PLC.</param>
public static byte[] ToByteArray(string value, int reservedLength)
{
return System.Text.Encoding.ASCII.GetBytes(value);
var length = value?.Length;
if (length > reservedLength) length = reservedLength;
var bytes = new byte[reservedLength];
if (length == null || length == 0) return bytes;
System.Text.Encoding.ASCII.GetBytes(value, 0, length.Value, bytes, 0);
return bytes;
}
/// <summary>