Type conversion question

H

Harald

Hi, I have two NewBie questions:

1. Can a string in C# contain any byte values in between (including 0
Bytes)?
2. How to convert a byte array (byte[]) into a string and vic versa?

Thanks for Your help
Regards, Harald
 
H

Harald

I forgot to mention, that I need the conversion to include Unicode <--->
ANSI translation
- Harald
 
M

Morten Wennevik

Hi Harald,

Take a look at the Encoding class.

You can translate a String to a byte[] and back to String like this:

String s = "Hello World";
byte[] bytes = MyEncoding.GetBytes(s);
String t = MyEncoding.GetString(bytes);

To translate to/from bytes you need to use the correct Encoding or
characters will get translated wrong as well as decoding a 16-bit Unicode
encoded byte array using a 7-bit ASCII encoding won't give much useful
information.

To get ANSI codepages use Encoding.GetEncoding and either provide a
numeric value or a string representation for the specific encoding you
need.

Encoding MyEncoding = Encoding.GetEncoding("ISO-8859-15"); // Nordic
bytes[] bytes = MyEncoding.GetBytes(UnicodeString);
 

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