Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unicode-to-string conversion in C#

Tags:

c#

.net

vb.net

How can I convert a Unicode value to its equivalent string?

For example, I have "రమెశ్", and I need a function that accepts this Unicode value and returns a string.

I was looking at the System.Text.Encoding.Convert() function, but that does not take in a Unicode value; it takes two encodings and a byte array.

I bascially have a byte array that I need to save in a string field and then come back later and convert the string first back to a byte array.

So I use ByteConverter.GetString(byteArray) to save the byte array to a string, but I can't get it back to a byte array.

like image 235
Bob Avatar asked Nov 15 '10 12:11

Bob


4 Answers

Use .ToString();:

this.Text = ((char)0x00D7).ToString();
like image 189
Andrew Avatar answered Nov 15 '22 14:11

Andrew


Try the following:

byte[] bytes = ...;

string convertedUtf8 = Encoding.UTF8.GetString(bytes);
string convertedUtf16 = Encoding.Unicode.GetString(bytes); // For UTF-16

The other way around is using `GetBytes():

byte[] bytesUtf8 = Encoding.UTF8.GetBytes(convertedUtf8);
byte[] bytesUtf16 = Encoding.Unicode.GetBytes(convertedUtf16);

In the Encoding class, there are more variants if you need them.

like image 20
Pieter van Ginkel Avatar answered Nov 15 '22 12:11

Pieter van Ginkel


To convert a string to a Unicode string, do it like this: very simple... note the BytesToString function which avoids using any inbuilt conversion stuff. Fast, too.

private string BytesToString(byte[] Bytes)
{
  MemoryStream MS = new MemoryStream(Bytes);
  StreamReader SR = new StreamReader(MS);
  string S = SR.ReadToEnd();
  SR.Close();
  return S;
}

private string ToUnicode(string S)
{
  return BytesToString(new UnicodeEncoding().GetBytes(S));
}
like image 2
Dan Sutton Avatar answered Nov 15 '22 13:11

Dan Sutton


UTF8Encoding Class

   UTF8Encoding uni = new UTF8Encoding();
   Console.WriteLine( uni.GetString(new byte[] { 1, 2 }));
like image 1
Ramiz Uddin Avatar answered Nov 15 '22 13:11

Ramiz Uddin