我正在尝试将字节数组转换为以逗号分隔的字符串。我只想将字节的值转换为字符串,以便通过TCP向另一台计算机发送字符串。
这是我现在运行的代码,它可以工作,但速度太慢了(字节数组有50000个元素)。你有更好的想法吗?
谢谢。
byte[] bytes = (byte[])dt.Rows[0]["LNL_BLOB"];
string foto="";
foreach (byte b in bytes)
{
foto = foto + "," + b.ToString();
}
我正在尝试将字节数组转换为以逗号分隔的字符串。我只想将字节的值转换为字符串,以便通过TCP向另一台计算机发送字符串。
这是我现在运行的代码,它可以工作,但速度太慢了(字节数组有50000个元素)。你有更好的想法吗?
谢谢。
byte[] bytes = (byte[])dt.Rows[0]["LNL_BLOB"];
string foto="";
foreach (byte b in bytes)
{
foto = foto + "," + b.ToString();
}
在进行大量字符串操作时,请使用StringBuilder。在这种特殊情况下,您也可以使用string.Join:
string foto = string.Join(",", bytes);
好的,你正在分配100000个字符串(一半来自ToString()调用,一半用于中间字符串)。您从未听说过字符串连接的危险以及StringBuilder的作用吗?
例如:
byte[] bytes = (byte[])dt.Rows[0]["LNL_BLOB"];
System.Text.StringBuilder foto=new System.Text.StringBuilder();
foreach (byte b in bytes)
{
foto.AppendFormat(",{0}",b);
}
return foto.ToString(); /* Or however you're using your string now */
byte[] data = // whatever you do to get the bytes
string sData = Convert.ToBase64String(data);
这里是该方法的文档。
当您想从字符串中获取字节数组时,只需使用Convert.FromBase64String方法即可。
byte[] imageData = Convert.FromBase64String(sData);
byte[] bytes = (byte[])dt.Rows[0]["LNL_BLOB"];
StringBuilder foto = new StringBuilder();
for(int i = 0; i < bytes.Length; i++) {
foto.Append(bytes[i].ToString());
if (i != (bytes.Length - 1)) foto.Append(",");
}