Create a random string

I am trying to generate a random string in .NET and convert to bytes, and found it a bit difficult. I need a complete set of possible characters, and I understand that a string can contain any character.

My code currently looks like this:

var plainText = new StringBuilder();
for (int j = 0; j < stringLength; ++j)
{
    plainText.Append((char)_random.Next(char.MinValue, char.MaxValue));
}
byte[] x = Encoding.Unicode.GetBytes(plainText.ToString());
string result = Encoding.Unicode.GetString(x);

Theoretically, plainTextand resultshould be the same. They are basically the same, but some of the original characters are lost, they seem to be characters in the range 55000-57000 - they are replaced by the symbol 65533.

I assume the problem is related to my encoding, but I thought Unicode would handle this correctly. I tried UTF8 and UTF32, but they give me the same problem.

Any thoughts?

+5
source share
2 answers

, 0xD800-0xDFFF (55296-57343), Unicode, . ( 0xD800-0xDBFF, 0xDC00-0xDFFF), ( UTF-16). 0xFFFD (65533). # UTF-16 , .

, (, _random.Next, ), .

+8

55296-57343 (0xD800-0xDFFF). . UTF-16 unicode.

, , , char - . , > 2 ^ 16 .

UTF-16.

+2

All Articles