Well, I got my HexString (PacketS) for example "70340A0100000000000000" I want to split every time after 2 chars and put it into an byte array (Stream).
Means {70, 34, 0A, 01, 00, 00, 00, 00, 00, 00, 00}
Well, I got my HexString (PacketS) for example "70340A0100000000000000" I want to split every time after 2 chars and put it into an byte array (Stream).
Means {70, 34, 0A, 01, 00, 00, 00, 00, 00, 00, 00}
The shortest path (.NET 4+) is (depending the length or origin):
byte[] myBytes = BigInteger.Parse("70340A0100000000000000", NumberStyles.HexNumber).ToByteArray();
Array.Reverse(myBytes);
myStram.write(myBytes, 0, myBytes.Length);
For previous versions string.length/2 also defines the length of a byte array than can be filled for each parsed pair. This byte array can be written on stream as above.
For both cases, if your origin string is too long, and you want to avoid a huge byte array, proceed with steps getting groups of N characters from your origin.
This actually worked perfect! I am sorry if your code does the same but I just do not understand.
public static byte[] ConvertHexStringToByteArray(string hexString)
{
if (hexString.Length % 2 != 0)
{
throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "The binary key cannot have an odd number of digits: {0}", hexString));
}
byte[] HexAsBytes = new byte[hexString.Length / 2];
for (int index = 0; index < HexAsBytes.Length; index++)
{
string byteValue = hexString.Substring(index * 2, 2);
HexAsBytes[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}
return HexAsBytes;