ArrayToByte

83 阅读1分钟
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); // 每个单元格的大小(int类型数组在内存中占用的字节数)
        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; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                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; i < rows; i++)
        {
            for (int j = 0; j < columns; j++)
            {
                // 提取 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; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                byte[] temp = BitConverter.GetBytes(floatArray[i, j]);
                for (int k = 0; k < temp.Length; k++)
                {
                    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; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                array[i, j] = 0;
            }
        }
        return array;
    }
}