• Advertisement
Sign in to follow this  

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

This topic is 4278 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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);
textBox1.Text = sb.ToString();

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

Share this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


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

Share this post


Link to post
Share on other sites
For those operations I always use

dim s as string
s = System.Text.Encoding.UTF8.GetString(data)
//data being an array of bytes


I have never had any problems with this.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement