converting array of byte data type to string.

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

Christiaan van Bergen

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
 
I

Ignacio Machin \( .NET/ C# MVP \)

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,
 
J

Jon Skeet [C# MVP]

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 ;)
 
J

Jon Skeet [C# MVP]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top