How to convert a string to an ushort array
How to convert a string to an ushort 开发者_JS百科array..
Thank you very much for your help.
Thanks, Lokesh
string s = "test";
ushort[] result = s.ToCharArray().Select(c => (ushort)c).ToArray();
Not sure if it's the best way, but it should work.
Edit: I didn't know string
implemented IEnumerable
. So actually you just need:
ushort[] result = s.Select(c => (ushort)c).ToArray();
Thanks to Jeff for pointing that out.
If you don't require verifiable IL, the fastest way (that avoids copying the string data entirely) that only uses the standard library is to use the unsafe overload of Encoding.GetBytes
:
fixed (char* src = str) {
fixed (ushort* dst = arr) {
Encoding.Unicode.GetBytes(src, str.Length, (byte*)dst, arr.Length * 2);
}
}
精彩评论