Converting from byte[] to string and viceversa???

  • Thread starter Thread starter Bob Rock
  • Start date Start date
B

Bob Rock

Hello,

a simple question (if you know the answer) ... how to convert from and array
of bytes to a string (and viceversa). I haven't the conversion to be simple
... but even using the Convert or the Encoding class I seem to be having
trouble accomplishing it.


Bob Rock
 
I would use Encoding.Default.GetBytes for the String->Byte [] conversion

and Encoding.Default.GetString for the Byte []->String conversion
 
Bob Rock said:
a simple question (if you know the answer) ... how to convert from and array
of bytes to a string (and viceversa). I haven't the conversion to be simple
.. but even using the Convert or the Encoding class I seem to be having
trouble accomplishing it.

You need to know what encoding to use.

See http://www.pobox.com/~skeet/csharp/unicode.html for an explanation
of what it's all about.
 
Dennis Myrén said:
I would use Encoding.Default.GetBytes for the String->Byte [] conversion

and Encoding.Default.GetString for the Byte []->String conversion

That's only applicable if you *do* want to use the default encoding for
the current computer though - which in many cases isn't the right
choice. Guessing isn't a good idea with character encodings.
 
Hehe.

Yes, i know that.
It was an _example_.

Dennis Myrén said:
I would use Encoding.Default.GetBytes for the String->Byte [] conversion

and Encoding.Default.GetString for the Byte []->String conversion

That's only applicable if you *do* want to use the default encoding for
the current computer though - which in many cases isn't the right
choice. Guessing isn't a good idea with character encodings.
 
Sahil Malik said:
System.Byte[] inputData;
string inputstream = System.Text.Encoding.ASCII.GetString(inputData) ;

Thats it !! :)

Again, that's it if Encoding.ASCII *happens* to be the encoding you
want.

The code is going to be simple virtually whatever encoding you're
interested in, but working out which encoding is the right one to use
is very important - much more so than your post implied.
 
Back
Top