converting array of byte data type to string.

  • Thread starter Thread starter shivaprasad
  • Start date Start date
S

shivaprasad

Hi all,

I am a Beginner to c#.
I Need to convert array of byte data type to string. How to do this..

ex:

byte[] bytes = new byte[1000];

this bytes get filled up. Now I need to convert to string.
How to do this..
 
Hi,

Why not use this function:

public string writeByteArrayToString(byte[] byteArray)
{
ASCIIEncoding ascii = new ASCIIEncoding();
char[] charArray = ascii.GetChars(byteArray);
return new string(charArray);
}

Don't forget to include System.Text

Cheers,
Christiaan
 
Hi,

You need to know the format the bytes are in, are they ASCII, UTF8 or what?

Then you use the correct Encoding class.


cheers,
 
Christiaan van Bergen said:
Why not use this function:

public string writeByteArrayToString(byte[] byteArray)
{
ASCIIEncoding ascii = new ASCIIEncoding();
char[] charArray = ascii.GetChars(byteArray);
return new string(charArray);
}

Don't forget to include System.Text

Reasons not to use this function:

1) Its name doesn't follow the .NET naming conventions
2) It creates a new instance of ASCIIEncoding for no reason
3) It creates a new char array for no reason
4) It's less clear than Encoding.ASCII.GetString(whatever);

You did ask ;)
 
Hi all,

I am a Beginner to c#.
I Need to convert array of byte data type to string. How to do this..

ex:

byte[] bytes = new byte[1000];

this bytes get filled up. Now I need to convert to string.
How to do this..

You need to choose the right encoding, and then ask it to decode your
bytes to a string. Unless your byte array is absolutely full of useful
data, you should specify how much of it to decode.

See http://www.pobox.com/~skeet/csharp/unicode.html for more
information.
 
Back
Top