[英]Converting string to byte array in C# (CSV)
I wrote a function to convert byte[]
to string
, and I add ";"我写了一个函数将
byte[]
转换为string
,并添加“;” after each byte.在每个字节之后。 Now I want to convert this
string
to byte[]
by splitting the string (similar to a CSV 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;
}
How could I write a function to convert this string to that byte array again?我怎么能写一个函数来再次将此字符串转换为该字节数组?
try this尝试这个
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
will be useful instead of String
(Performance wise). StringBuilder
将代替String
有用(性能方面)。
With StringBuilder
:使用
StringBuilder
:
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(objStringBuilder.ToString());
with String
:与
String
:
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(objString);
I guess that you want to get rid of the ;
我猜你想摆脱
;
when converting also.转换时也。 I think you want to do something like this:
我想你想做这样的事情:
byte[] result = Encoding.UTF8.GetBytes(s.Replace(";",""));
This will fail if the original byte array actually contains a ;
如果原始字节数组实际上包含一个
;
这将失败;
that is valid data, but in that case you will have lots of problems anyway since your "CSV" file will be wrongly formatted.这是有效数据,但在这种情况下,无论如何您都会遇到很多问题,因为您的“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);
I know you already know the answer by now... but this code solves the problem, i hope it helps someone else.我知道你现在已经知道答案了……但是这段代码解决了这个问题,我希望它可以帮助别人。
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;
}
I like using number styles hex number.我喜欢使用数字样式十六进制数字。
Simply :)简单地 :)
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.