Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# byte array to string, and vice-versa

Tags:

c#

I have some C++ code that persists byte values into files via STL strings & text i/o, and am confused about how to do this in C#.

first I convert byte arrays to strings & store each as a row in a text file:

 StreamWriter F
 loop
 {
   byte[] B;       // array of byte values from 0-255 (but never LF,CR or EOF)
   string S = B;   // I'd like to do this assignment in C# (encoding? ugh.) (*)
   F.WriteLine(S); // and store the byte values into a text file
 }

later ... I'd like to reverse the steps and get back the original byte values:

  StreamReader F;   
  loop
  {
    string S = F.ReadLine();   // read that line back from the file
    byte[] B = S;              // I'd like to convert back to byte array (*)
  }

How do you do those assignments (*) ?

like image 514
tpascale Avatar asked Aug 19 '13 03:08

tpascale


1 Answers

class Encoding supports what you need, example below assumes that you need to convert string to byte[] using UTF8 and vice-versa:

string S = Encoding.UTF8.GetString(B);
byte[] B = Encoding.UTF8.GetBytes(S);

If you need to use other encodings, you can change easily:

Encoding.Unicode
Encoding.ASCII
...
like image 138
cuongle Avatar answered Nov 15 '22 11:11

cuongle