[.net] converting a byte[] to a string.

Recommended Posts

as practice, im reading in an arbitrary file using Stream. i store everything into a buffer of byte[]. then i convert each byte into a char, which then i use to append to a string. then i display the results into a textbox.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < buffer.Length; ++i)
{
sb.Append((char)buffer[i]);
textBox1.Text = sb.ToString();


I know there must be a better way to converte a byte[] to a string. but how??

Share on other sites
string Str=BitConverter.ToString(ByteArray);

Share on other sites
many thanks! i would've never thought of that.
still quite new to C#.

Share on other sites
i tried this. but i get a bunch of negative values.
i think it might have something to do with this bit covnerting from a byte directly to a string.

the way it worked before was to convert each byte to a char, then convert to a string by appending the char's.

Share on other sites
Hrm. Indeed. Not sure, I've always used proper TextReaders for bytestream -> string stuff.

[edit:

        Byte[] Bits ={ 109, 111, 111, 46 };        String str = new string(Array.ConvertAll<Byte, Char>(Bits, Convert.ToChar));                Console.WriteLine("str: {0}", str);        // moo.

Share on other sites
okay, this is kinda confusing...but i did figure out a way.

char[] charArray = Array.ConvertAll<byte, char>(buffer, Convert.ToChar);StringBuilder b = new StringBuilder();b.Append(charArray);textBox1.Text = b.ToString();

Share on other sites
i've still hardly touched c#, but what about:
byte[] b = Encoding.ASCII.GetBytes("roflcopter");string s = Encoding.ASCII.GetString(b);

would this be a proper method? (i need to get back to learning c# again...)

Share on other sites
Oh yeah, going through the encoding is probably the proper way. Always forget about that...

Share on other sites
Encoding?
that's new to me. didnt even know that existed.

Share on other sites
For those operations I always use
dim s as strings = System.Text.Encoding.UTF8.GetString(data)//data being an array of bytes

I have never had any problems with this.

Share on other sites
S.T.Encoding is *the* way.

Create an account

Register a new account

• Forum Statistics

• Total Topics
628347
• Total Posts
2982204

• 10
• 9
• 24
• 11
• 9