Found on the Internet this snippet. For some reason, I have questions in the results.

var unicodeString= "Привет"; Encoding ascii = Encoding.ASCII; Encoding unicode = Encoding.Unicode; byte[] unicodeBytes = unicode.GetBytes(unicodeString); byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes); char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)]; ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0); string asciiString = new string(asciiChars); 
  • The encoding of a string in unicodeString is determined by the encoding of the source file. Check it through the file properties in the VS project tree. - ߊߚߤߘ
  • ummm and how to view it? I have no such menu in the context menu - Zevra
  • @Arhad \ u0420 \ u043e \ u0441 \ u0441 \ u0438 \ u044f what is the encoding? - Zevra
  • This is guaranteed unicode, regardless of the encoding of the source file. - ߊߚߤߘ
  • @Arhad I want the word Hello converted to unicode. Are there any errors in my code? - Zevra

1 answer 1

In C #, strings are not encoded. But an array of bytes can be a representation of a string in one or another encoding. Therefore, the encoding question appears only when a string is converted into a set of bytes or a set of bytes back into a string (as well as records to files and other streams, which are also a set of bytes).

Therefore, it is not necessary to recode a string, and it is meaningless.

In your case, you get the bytes of the "Привет" string in UTF-16 (the unicodeBytes variable), then transcode them into ASCII (the asciiBytes variable). The problem, however, is that ASCII does not have Cyrillic characters at all, so they are replaced by bytes for question marks.

Further you decode give ASCII * in line, and see in it natural question marks.


* By the way, it can be made easier:

 string asciiString = ascii.GetString(asciiBytes); 
  • pliz tell me what to change to - Zevra
  • one
    @Zevra: Nothing needs to be changed. The string in C # does not have an encoding; it cannot be changed. - VladD