ByteArray to String

  • Thread starter Thread starter Chris
  • Start date Start date
C

Chris

What is the best way to convert a bytearray into a string ?

I thought I could do it using the code below, but is there anything
faster/easier than this? Thanks!

Chris



int aLength = 100000;
byte[] myByteArray = new byte[aLength ];
string myString = "";


for (int i=0; i<aLength ; i++)
{
myString += (char) myByteArray;
}

//work with this new string: cut out every char=='A'
myString.split('A');

....
 
I've been doing this is VC# Express 2005 Beta:

ASCIIEncoding AE = new ASCIIEncoding();
string TextString = AE.GetString(byte-array);

Don't know if it works in other versions, so you'll need to check in your
specific VS release.

HTH
Steve
 
Chris,

Do you know the encoding of the string? If so, then use the appropriate
encoder class (AsciiEncoder, UnicodeEncoder, etc, etc).

You would just call the GetString method on the encoder class at that
point.

Hope this helps.
 
First of all you are assuming that your array of bytes is an array of
chars, which might be risky.

However, String has a constructor that takes an array of characters.
 
Chris said:
What is the best way to convert a bytearray into a string ?

That all depends on the source of the byte array. What kind of data
does it represent? If it's text data, what encoding was used to encode
it? If it's arbitrary binary data (eg an mp3 file) you need to use
something like base64.

See http://www.pobox.com/~skeet/csharp/unicode.html

By the way, concatenating strings in a loop like that is a
performance-killer. See
http://www.pobox.com/~skeet/csharp/stringbuilder.html for more
information.

Jon
 

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

Back
Top