2

How to convert a string to an ushort array..

Thank you very much for your help.

Thanks, Lokesh

Lokesh
  • 829
  • 2
  • 14
  • 26
  • What are you going to do with this array - do you need a trailing zero because you're going to pass it a zero-terminated string? – Rup Jul 29 '10 at 11:16

2 Answers2

4
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.

fearofawhackplanet
  • 52,166
  • 53
  • 160
  • 253
0

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);
   }
}
Pavel Minaev
  • 99,783
  • 25
  • 219
  • 289