I don’t know how to encode each character of a string in a loop into an ASCII number of an element. There is a str - the string english \ russian letters.

It works

byte[] bytes = Encoding.GetEncoding(1251).GetBytes(str); 

And this is not - he writes, str[i] underlines that the char cannot be converted to char []. Maybe this is due to the fact that in the first case the array, but not here.

 Encoding.GetEncoding(1251).GetBytes(str[i]) 

I would have the representation of a number in int in order to calculate the character position in the alphabet through it

  • str[i] is not a string, but a character - VladD
  • In general, there are no Russian letters in ASCII, so your task, as it is formulated, is impracticable. - VladD pm
  • ASCII and 1251 are not the same thing - Andrey NOP
  • I don't really understand this, why byte[] bytes = Encoding.GetEncoding(1251).GetBytes(str); for (int i = 0; i < bytes.Length; i++) Console.WriteLine(bytes[i]); byte[] bytes = Encoding.GetEncoding(1251).GetBytes(str); for (int i = 0; i < bytes.Length; i++) Console.WriteLine(bytes[i]); gives codes for Russian characters? - ImmRaytal
  • Yes, str [i] symbol, but for the symbol does not work? - ImmRaytal

2 answers 2

Windows-1251 is single-byte encoding. Consequently, in the final array, each byte will match one character of the string with the same index. Therefore, you can first convert the entire string into an array of bytes in this encoding, and then iterate over the array, getting character codes.

 var str = "Привет"; byte[] bytes = Encoding.GetEncoding(1251).GetBytes(str); for (int i = 0; i < bytes.Length; i++) Console.WriteLine(str[i] + " - " + bytes[i]); 

    The GetBytes method GetBytes input of a string or an array of characters, but not a single character of type char . Therefore, you should convert the character to a string using the ToString method.

    The resulting array will always be 1. This is the character code.

     var str = "Привет"; for (int i = 0; i < str.Length; i++) { byte[] bytes = Encoding.GetEncoding(1251).GetBytes(str[i].ToString()); Console.WriteLine(str[i] + " - " + bytes[0]); } 
    • I apologize, but what is 'c' - ImmRaytal
    • The symbol of any char, in this case c , Vitali Shebanits,
    • I hope you will not mind my edits. - Alexander Petrov
    • Why pull a character out of a string, turn it into a string, and then encode it, if it can simply transcode the entire string in advance? - tym32167
    • @ tym32167 - the question was originally posed by the top-starter that way. The answer is formally correct. - Alexander Petrov