[英]Converting string to byte array in C# (CSV)
我寫了一個函數將byte[]
轉換為string
,並添加“;” 在每個字節之后。 現在我想通過拆分字符串(類似於 CSV 字符串)將此string
轉換為byte[]
。
public string ByteArrayToString(byte[] byteArray,string s)
{
for (int i = 0; i < byteArray.Length; i++)
{
s += byteArray[i].ToString() + ";";
}
s = s.Substring(0, s.Length - 1);
return s;
}
我怎么能寫一個函數來再次將此字符串轉換為該字節數組?
嘗試這個
var byteArray = new byte[] {123, 11, 111};
var stringBytes = string.Join(";", byteArray.Select(b => b.ToString()));
var newByteArray = stringBytes.Split(';').Select(s => byte.Parse(s)).ToArray();
考慮使用拆分字符串
StringBuilder
將代替String
有用(性能方面)。
使用StringBuilder
:
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(objStringBuilder.ToString());
與String
:
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(objString);
我猜你想擺脫;
轉換時也。 我想你想做這樣的事情:
byte[] result = Encoding.UTF8.GetBytes(s.Replace(";",""));
如果原始字節數組實際上包含一個;
這將失敗;
這是有效數據,但在這種情況下,無論如何您都會遇到很多問題,因為您的“CSV”文件格式錯誤。
str.Split(new char[]{';'},
StringSplitOptions.RemoveEmptyEntries).Select(s => byte.Parse(s)).ToArray();
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
return encoding.GetBytes(yourStringVariable);
我知道你現在已經知道答案了……但是這段代碼解決了這個問題,我希望它可以幫助別人。
int counter= 0;
string cadena = "8,5,6,3,4,6,3"
string[] foto = cadena.Split(',');
byte[] fotoFinal = new byte[foto.Length];
foreach (string s in foto)
{
fotoFinal[contador] = Convert.ToByte(s);
counter++;
}
string[] sbytes = sl.Split(',');
byte[] b = new byte[sbytes.Length];
for (int j = 0; j < sbytes.Length; j++)
{
byte newByte = byte.Parse(sbytes[j], System.Globalization.NumberStyles.HexNumber);
b[j] = newByte;
}
我喜歡使用數字樣式十六進制數字。
簡單地 :)
public static byte[] Bytes ( this string Key )
{
return Enumerable.Range(0, Key.Binary().Length / 8 )
.Select(Index => Convert.ToByte(
Key.Binary().Substring(Index * 8, 8), 2))
.ToArray();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.