I find myself converting 1D byte and single arrays to 2D by doing the following. I suspect it is probably as fast as other methods, but perhaps there is a cleaner simpler paradigm? (Linq?)
private static byte[,] byte2D(byte[] input, int height, int width)
{
byte[,] output = new byte[height, width];
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
output[i, j] = input[i * width + j];
}
}
return output;
}
private static Single[,] single2D(byte[] input, int height, int width)
{
Single[,] output = new Single[height, width];
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
output[i, j] = (Single)input[i * width + j];
}
}
return output;
}
This doesn't help with making the code inside the methods cleaner, but I noticed that you have 2 basically identical methods that differ only in their types. I suggest using generics.
This would let you define your method only once. Using the where
keyword, you can even limit the kind of types you allow your method to work on.
private static T[,] Make2DArray<T>(T[] input, int height, int width)
{
T[,] output = new T[height, width];
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
output[i, j] = input[i * width + j];
}
}
return output;
}
You would call this method like this
int[] a; //or any other array.
var twoDArray = Make2DArray(a, height, width);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With