开发者

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

开发者 https://www.devze.com 2022-12-15 09:10 出处:网络
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 th开发者_JS百科e same byte array. Same length and everyth

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 th开发者_JS百科e 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?


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

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


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消