bobber205
bobber205

Reputation: 13372

Byte[] to String to Byte[] -- How to do so?

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?

Upvotes: 2

Views: 607

Answers (4)

Eden
Eden

Reputation: 709

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.

Upvotes: 1

David R Tribble
David R Tribble

Reputation: 12204

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).

Upvotes: 1

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422076

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

string s = Convert.ToBase64String(byteArray);
byte[] decoded = Convert.FromBase64String(s);

Upvotes: 5

Michael Petrotta
Michael Petrotta

Reputation: 60922

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.

Upvotes: 2

Related Questions