I want to encode unicode codepoints to utf8 manually. I wrote the following C# code. I testet it with some cases I know but I would like to know if its correct for all inputs. I know that Unicode codepoints are undefined beyond 10FFFFhex but I dont care about that. Therefore the output of my method might be more than 4 bytes.private byte[] CodePointToUtf8 (int codepoint){    if (codepoint < 0x80) {        return new byte[]{             (byte)(codepoint)         };    } else if (codepoint < 0x800) {                 return new byte[]{             (byte)(0xC0 | (codepoint << 21 >> 27)),             (byte)(0x80 | (codepoint << 26 >> 26))        };    } else if (codepoint < 0x10000) {        return new byte[] {            (byte)(0xE0 | (codepoint << 16 >> 28)),            (byte)(0x80 | (codepoint << 20 >> 26)) ,            (byte)(0x80 | (codepoint << 26 >> 26))        };    } else if (codepoint < 0x200000) {        return new byte[] {            (byte)(0xF0 | (codepoint << 11 >> 29)),            (byte)(0x80 | (codepoint << 14 >> 26)),            (byte)(0x80 | (codepoint << 20 >> 26)) ,            (byte)(0x80 | (codepoint << 26 >> 26))        };    } else if (codepoint < 0x4000000) {        return new byte[] {            (byte)(0xF8 | (codepoint << 6 >> 30)),            (byte)(0x80 | (codepoint << 8 >> 26)),            (byte)(0x80 | (codepoint << 14 >> 26)),            (byte)(0x80 | (codepoint << 20 >> 26)) ,            (byte)(0x80 | (codepoint << 26 >> 26))        };    } else {        return new byte[] {            (byte)(0xFC | (codepoint << 1 >> 31)),            (byte)(0x80 | (codepoint << 2 >> 26)),            (byte)(0x80 | (codepoint << 8 >> 26)),            (byte)(0x80 | (codepoint << 14 >> 26)),            (byte)(0x80 | (codepoint << 20 >> 26)) ,            (byte)(0x80 | (codepoint << 26 >> 26))        };    }}Bonus question: Is there an build in way to do that?
C# Encode Unicode Codepoints to UTF8 Manually
c#;unicode;utf 8
Yes, the code is correct for all valid code points. I was first confused about the double shifts, since I have never seen them before, but they do their job well. Other authors typically do a single >> followed by a bit mask, e.g. (codepoint >> 12) & 0x3F to skip the 12 bits to the right and take the next 6 bits. That way, the numbers can be verified more easily, since they are smaller. Plus, all the 01xxxxxx bytes have the same bitmask.Your code omits some validity checks:codepoint could be < 0codepoint could be between 0xD800 and 0xDFFFOther than these, it is perfect.I know for sure that this conversion is built-in into C#, I just don't know where. Try loading a file into a string using the UTF-8 encoding. During that loading, the built-in conversion code gets called.