How to convert string to ushort array

How to convert string to ushort array.

Many thanks for your help.

Thanks Lokesh

+1
source share
2 answers
string s = "test"; ushort[] result = s.ToCharArray().Select(c => (ushort)c).ToArray(); 

Not sure if this is the best way, but it should work.

Edit: I did not know the string implemented by IEnumerable . So you just need to:

 ushort[] result = s.Select(c => (ushort)c).ToArray(); 

Thanks Jeff for pointing this out.

+3
source share

If you don't need a proven IL, the fastest way (which allows you to completely copy string data) that uses only the standard library is to use the unsafe Encoding.GetBytes overload:

 fixed (char* src = str) { fixed (ushort* dst = arr) { Encoding.Unicode.GetBytes(src, str.Length, (byte*)dst, arr.Length * 2); } } 
0
source share

All Articles