我想通过套接字发送一个二维字符串数组(string [n,m]),它必须转换为字节数组。我怎么能这样做?
答案 0 :(得分: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();
}
}
并将字节数组转换回2D字符串数组:
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;
}
}