0

可能重复:
如何在 C# 中将 int[,] 转换为 byte[]

我想通过套接字发送一个二维字符串数组(string[n,m]),它必须转换为字节数组。我怎样才能做到这一点?

4

1 回答 1

0

您可以使用前 8 个字节来存储数组的维度:

public static byte[] ToByteArray(string[,] input)
{
    using (var stream = new MemoryStream())
    using (var writer = new BinaryWriter(stream, Encoding.UTF8))
    {
        var rows = input.GetLength(0);
        var cols = input.GetLength(1);
        writer.Write(rows);
        writer.Write(cols);
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                writer.Write(input[i, j]);
            }
        }
        return stream.ToArray();
    }
}

并将字节数组转换回二维字符串数组:

public static string[,] FromByteArray(byte[] input)
{
    using (var stream = new MemoryStream(input))
    using (var reader = new BinaryReader(stream, Encoding.UTF8))
    {
        var rows = reader.ReadInt32();
        var cols = reader.ReadInt32();
        var result = new string[rows, cols];
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                result[i, j] = reader.ReadString();
            }
        }
        return result;
    }
}
于 2012-10-01T18:00:53.090 回答