If you donโt care too much about using a particular encoding and your code is performance critical (for example, itโs a kind of database serializer and should run millions of times per second), try
fixed (void* ptr = tempText) { System.Runtime.InteropServices.Marshal.Copy(new IntPtr(ptr), tempByte, 0, len); }
Edit : Marshal.Copy was about ten times faster than UTF8.GetBytes and got the UTF-16 encoding. To convert it to a string, you can use:
fixed (byte* bptr = tempByte) { char* cptr = (char*)(bptr + offset); tempText = new string(cptr, 0, len / 2); }
source share