If you have an existing byte[]
array, you can't change the size of it.
You can create a new array of a different size using Array.Resize()
(this changes the array's reference to reference a new one) or you can create a new array of the correct size and copy the prefix bytes and the appended bytes into it.
This is very easy with Linq if you're using .NET 5.0 or later:
bufferByte = bufferByte.Concat(Convert.FromHexString(s)).ToArray();
Full sample:
using System;
using System.Linq;
static class Program
{
public static void Main()
{
// this is my string
string s = "7C04048404048C04049404059C0405";
// this is my byte array to which I want to append the string, keeping the same format of the array
var bufferByte = new byte[] { 0x40, 0x03, 0xE8, 0x03, 0xE8, 0x49 };
bufferByte = bufferByte.Concat(Convert.FromHexString(s)).ToArray();
Console.WriteLine(Convert.ToHexString(bufferByte)); // 4003E803E8497C04048404048C04049404059C0405
}
}
Try it online: https://dotnetfiddle.net/9v54EE
If you're using an earlier version of .NET you'll have to write your own converter for the hex string:
using System;
using System.Linq;
public static class Program
{
public static void Main()
{
// this is my string
string s = "7C04048404048C04049404059C0405";
// this is my byte array to which I want to append the string, keeping the same format of the array
var bufferByte = new byte[] { 0x40, 0x03, 0xE8, 0x03, 0xE8, 0x49 };
bufferByte = bufferByte.Concat(StringToByteArray(s)).ToArray();
Console.WriteLine(ByteArrayToString(bufferByte)); // 4003E803E8497C04048404048C04049404059C0405
}
public static string ByteArrayToString(byte[] ba)
{
return BitConverter.ToString(ba).Replace("-", "");
}
public static byte[] StringToByteArray(string hex)
{
int numberChars = hex.Length;
byte[] bytes = new byte[numberChars / 2];
for (int i = 0; i < numberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
}
Try it online: https://dotnetfiddle.net/vKCHYs
I copied the conversion code from here: https://stackoverflow.com/a/311179/106159