Sign in to follow this  
GekkoCube

[.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 this post


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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this