Converting string to byte array in C# (CSV)
11,093
Solution 1
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();
Solution 2
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.
Solution 3
Consider using Split String
Solution 4
StringBuilder
will be useful instead of String
(Performance wise).
With StringBuilder
:
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(objStringBuilder.ToString());
with String
:
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(objString);
Related videos on Youtube
Author by
sss
Updated on June 04, 2022Comments
-
sss almost 2 years
I wrote a function to convert
byte[]
tostring
, and I add ";" after each byte. Now I want to convert thisstring
tobyte[]
by splitting the string (similar to a CSV string).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?
-
Jonas Elfström over 13 yearsIs the string like
T;*;|;m;
or84;42;124;109;
? -
Rune FS over 13 years"thanks BUT it couldn't help me! i want to split my string by ";" then put it in the array then convert it to byte [] " try to write some pseudo code for this so we can see what you want. My understading of that qoute is you want to cast a string[] to a byte[] while interpreting the string values as a byte each. Which is not possible. You need to convert each value
-
-
sss over 13 yearsthanks BUT it couldn't help me! i want to split my string by ";" then put it in the array then convert it to byte []
-
sss over 13 yearsthanks BUT it couldn't help me! i want to split my string by ";" then put it in the array then convert it to byte []
-
Itay Karo over 13 yearsTry this:
Encoding.UTF8.GetBytes(str.Replace(";", string.Empty);
-
Rune FS over 13 yearswont work byteArray[i].ToString() + ";" does not concatenate the byte values as char but uses 1-3 char pr. byte
-
Rune FS over 13 yearsthe values are "printed" some 32 is "32" not " " as your code expects