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);
Share:
11,093

Related videos on Youtube

sss
Author by

sss

Updated on June 04, 2022

Comments

  • sss
    sss almost 2 years

    I wrote a function to convert byte[] to string, and I add ";" after each byte. Now I want to convert this string to byte[] 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
      Jonas Elfström over 13 years
      Is the string like T;*;|;m; or 84;42;124;109;?
    • Rune FS
      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
    sss 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 []
  • sss
    sss 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 []
  • Itay Karo
    Itay Karo over 13 years
    Try this: Encoding.UTF8.GetBytes(str.Replace(";", string.Empty);
  • Rune FS
    Rune FS over 13 years
    wont work byteArray[i].ToString() + ";" does not concatenate the byte values as char but uses 1-3 char pr. byte
  • Rune FS
    Rune FS over 13 years
    the values are "printed" some 32 is "32" not " " as your code expects