// Do NOT use on arbitrary bytes; only use on GetBytes's output on the SAME system staticstringGetString(byte[] bytes) { char[] chars = newchar[bytes.Length / sizeof(char)]; System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length); returnnewstring(chars); }
使用特定编码转换
如果需要考虑编码,.NET提供了方便的方法:
1 2 3
conststring data = "A string with international characters: Norwegian: ÆØÅæøå, Chinese: 喂 谢谢"; var bytes = System.Text.Encoding.UTF8.GetBytes(data); var decoded = System.Text.Encoding.UTF8.GetString(bytes);
不使用编码提及的获取方法
要避免提及编码,可以使用指针的方式获取字符串存储的实际字节:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// using System.Runtime.InteropServices unsafebyte[] GetRawBytes(String s) { if (s == null) returnnull; var codeunitCount = s.Length; /* We know that String is a sequence of UTF-16 code units and such code units are 2 bytes */ var byteCount = codeunitCount * 2; var bytes = newbyte[byteCount]; fixed(void* pRaw = s) { Marshal.Copy((IntPtr)pRaw, bytes, 0, byteCount); } return bytes; }