0
可能重複:
How to convert an int[,] to byte[] in C#轉換字符串[,]到字節爲在C#.NET發送由插座
我想發送2D字符串數組(串[N,M ])通過套接字,它必須被轉換爲字節數組。我怎樣才能做到這一點?
可能重複:
How to convert an int[,] to byte[] in C#轉換字符串[,]到字節爲在C#.NET發送由插座
我想發送2D字符串數組(串[N,M ])通過套接字,它必須被轉換爲字節數組。我怎樣才能做到這一點?
您可以使用前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;
}
}
的http://計算器.COM /問題/ 3322473 /如何對轉換-AN-INT-到字節在-C-銳 – Thousand