views:

123

answers:

4

Ignore the reasons why someone would want to do this.... :)

I want to be able to take some bytes, covert them to a string, then later back to the same byte array. Same length and everything.

I've tried using the ASCIIEncoder class (works for only text files) and Unicode Encoder class (only works so far for arrays 1024*n big. I assume this is because of the equal length of each character) with no success.

Is there any easy way to do this? I assume I should probably write my own functions to do so huh?

+2  A: 

Base64 is great at problems like this.

string str = Convert.ToBase64String(inArray);
...
byte[] ourArray = Convert.FromBase64String(str);

Note that the resulting string will be larger (of course) than your original array.

Michael Petrotta
+5  A: 

Use Base64 encoding. It's not space-efficient though.

string s = Convert.ToBase64String(byteArray);
byte[] decoded = Convert.FromBase64String(s);
Mehrdad Afshari
Thank you! Thank you! :DThe solution I was trying to write myself was extremely slow...
bobber205
A: 

If you know the encoding of your string (I would guess it is UTF8) then simply use the encoding class:

Encoding.UTF8.GetBytes
Encoding.UTF8.GetString

Encoding class can be found in the System.Text namespace

Y.

Eden
The byte[] array is being read from a file so I don't know its encoding.
bobber205
+1  A: 

If you don't mind the doubling of space required to store each 8-bit byte into a 16-bit char, and you don't need the string to be composed of printable characters, you could do it the direct way:

string BytesToString(byte[] b)
{
    StringBuilder  s;    

    s = new StringBuilder(b.Length);
    for (int i = 0;  i < b.Length;  i++)
        s[i] = (char) b[i];    // Cast not really needed
    return s.ToString();
}    

byte[] StringToBytes(string s)
{
    byte[]  b;    

    b = new byte[s.Length];
    for (int i = 0;  i < b.Length;  i++)
        b[i] = (byte) s[i];
    return b;
}

You could write more elaborate code to pack two 8-bit bytes into each 16-bit Unicode char, but then you'd have to handle the special cases of odd byte array lengths (which could be done using an extra sentinel byte in the last character).

Loadmaster
I tried this method using just regular strings and the + operator. Was mad slow. Is that because I didn't use a StringBuilder (like I usually do)?
bobber205
Yes. Typically, each `+` operator involves the overhad of creating a new temporary `StringBuilder` object, initializing it with the partially built string, appending the next character, which typically causes the internal buffer array in `StringBuilder` to be reallocated and copied (again). And this happens for each loop iteration. So, yeah, it's generally a very slow way to do it. Using an explicit `StringBuilder` having a sufficiently large buffer allocated to it eliminates all of that overhead.
Loadmaster