public class ArrayToByteHelper
{
// 将二维int数组转换为byte数组
public static byte[] IntArrayToByteArray(float[,] intArray)
{
int width = intArray.GetLength(0)
int height = intArray.GetLength(1)
int cellSize = sizeof(float)
byte[] byteArray = new byte[width * height * cellSize]
Buffer.BlockCopy(intArray, 0, byteArray, 0, byteArray.Length)
return byteArray
}
// 将byte数组转换为二维float数组
public static float[,] ByteArrayToFloatArray(byte[] bytes, int width, int height)
{
float[,] floatArray = new float[width, height]
int bytesPerFloat = sizeof(float)
for (int y = 0
{
for (int x = 0
{
int index = (y * width + x) * bytesPerFloat
floatArray[x, y] = BitConverter.ToSingle(bytes, index)
}
}
return floatArray
}
// 将byte数组转换为二维float数组
public static float[,] Convert(byte[] byteArray, int rows, int columns)
{
if (byteArray.Length != rows * columns * 4)
{
throw new ArgumentException("The byte array length does not match the specified dimensions.")
}
float[,] floatArray = new float[rows, columns]
int index = 0
for (int i = 0
{
for (int j = 0
{
// 提取 4 个字节并转换为 float
floatArray[i, j] = BitConverter.ToSingle(byteArray, index)
index += 4
}
}
return floatArray
}
// 将二维float数组转换为byte数组
public static byte[,] FloatArrayToByteArray(float[,] floatArray)
{
int rows = floatArray.GetLength(0)
int cols = floatArray.GetLength(1)
byte[,] byteArray = new byte[rows, cols * 4]
for (int i = 0
{
for (int j = 0
{
byte[] temp = BitConverter.GetBytes(floatArray[i, j])
for (int k = 0
{
byteArray[i, j * 4 + k] = temp[k]
}
}
}
return byteArray
}
// 将二维float数组中的所有元素设置为0
public static float[,] SetArrayToZero(float[,] array)
{
int rows = array.GetLength(0)
int cols = array.GetLength(1)
for (int i = 0
{
for (int j = 0
{
array[i, j] = 0
}
}
return array
}
}