There's quite some issues with what you're actually asking, especially if you don't want to write code per type. Luckily there aren't that many numeric type in the BCL, so you could write it all out once or even let it be generated.
A very naive approach is shown below:
public static void Main()
{
int[] intArray = new int[] { 1, 2, 42, };
byte[] intOutput = ConvertToByteArray(intArray, sizeof(int));
for (int i = 0; i < intOutput.Length; i++)
{
Console.Write("{0:x2} ", intOutput[i]);
if ((i + 1) % singleItemSize == 0)
{
Console.WriteLine();
}
}
}
private static byte[] ConvertToByteArray<T>(T[] input, int singleItemSize)
where T : struct,
IComparable,
IComparable<T>,
IConvertible,
IEquatable<T>,
IFormattable
{
var outputArray = new byte[input.Length * singleItemSize];
// Iterate over the input array, get the bytes for each value and append them to the output array.
for (int i = 0; i < input.Length; i++)
{
var thisItemBytes = GetBytes(input[i]);
Buffer.BlockCopy(thisItemBytes, 0, outputArray, i * singleItemSize, singleItemSize);
}
return outputArray;
}
private static byte[] GetBytes<T>(T input)
where T : struct,
IComparable,
IComparable<T>,
IConvertible,
IEquatable<T>,
IFormattable
{
if (typeof(T) == typeof(int))
{
return BitConverter.GetBytes(Convert.ToInt32(input));
}
else if (typeof(T) == typeof(float))
{
return BitConverter.GetBytes(Convert.ToSingle(input));
}
else
{
throw new ArgumentException("T");
}
}
This outputs the following (depending on your system's endianness):
01 00 00 00
02 00 00 00
2a 00 00 00
And so the ConvertToByteArray()
method delivers a useless array of 12 bytes given the input of int[] { 1, 2, 42 }
. It is useless because you don't know whether that array contains 12 bytes, 6 chars, 3 ints, 3 floats or 3 unsigned integers.
Apart from that, there's a lot of (performance) problems with the shown code, which I'm sure can be simplified.
Instead perhaps you can find another solution for this seemingly XY problem.