Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Short Array to String C#

Tags:

c#

utf-16

Is it possible to convert short array to string, then show the text?

short[] a = new short[] {0x33, 0x65, 0x66, 0xE62, 0xE63};

There are utf16 (thai characters) contains in the array. How can it output and show the thai and english words?

Thank you.

like image 652
Fusionmate Avatar asked Apr 04 '13 15:04

Fusionmate


2 Answers

You can get a string from a UTF16 byte array using this method:

System.Text.Encoding.Unicode.GetString(bytes)

However, this only accepts an byte array. So you first have to transform your shorts to bytes:

var bytes = a.SelectMany(x => BitConverter.GetBytes(x)).ToArray();

Or slightly more verbose but much more efficient code:

var bytes = new byte[a.Length * 2];
Buffer.BlockCopy(a, 0, bytes, 0, a.Length * 2);
like image 55
JustAnotherUserYouMayKnow Avatar answered Oct 12 '22 10:10

JustAnotherUserYouMayKnow


I'm slightly ripping off everyone else's answers, but here is a cleaner way of doing the same thing:

short[] shorts = new short[] { 0x33, 0x65, 0x66, 0xE62, 0xE63 };
char[] chars = Array.ConvertAll(shorts, Convert.ToChar);
string result = new string(chars);
like image 7
Buh Buh Avatar answered Oct 12 '22 12:10

Buh Buh