C# ASCII or Unicode

2019-05-01 11:58发布

问题:

hi im a beginner in programming and network development. i have a question regarding ASCII and Unicode encoding.

in msdn and other web examples do the following:

byte[] byteData = Encoding.ASCII.GetBytes(data);

is this because these code samples are old? shouldn't it be:

byte[] byteData = Encoding.Unicode.GetBytes(data);

thanks for your input!

回答1:

It depends - do you want the result to be in ASCII or UTF-16? Each is wrong when you want the other.

If you're talking some network protocol, you must find out which character encoding is expected by the protocol. Use the wrong encoding, and Bad Things Will Happen.

Of course ASCII has massive restrictions - it's very English-based (Latin characters only, no accents) but it's correct for some protocols. Others may use UTF-16 (Encoding.Unicode), UTF-8 or other encodings... or they'll let you specify the encoding yourself within the protocol.



标签: c# unicode ascii