Convert Unicode-to-string to C #

How to convert a Unicode value to its equivalent string?

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

I looked at the System.Text.Encoding.Convert () function, but this does not take Unicode value; It takes two encodings and a byte array.

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

So I use ByteConverter.GetString (byteArray) to save an array of bytes to a string, but I cannot return it to an array of bytes.

+2
source share
6 answers

Try the following:

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

Another way to use `GetBytes ():

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

There are more options in the Encoding class if you need them.

+5
source

Use .ToString ();

 this.Text = ((char)0x00D7).ToString(); 
+4
source

To convert a string to a Unicode string, do it like this: very simple ... pay attention to the BytesToString function, which avoids the use of built-in conversion elements. 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)); } 
+3
source

UTF8Encoding Class

  UTF8Encoding uni = new UTF8Encoding(); Console.WriteLine( uni.GetString(new byte[] { 1, 2 })); 
+1
source

There are different types of coding. You can try some of them to check if your stream is converted correctly:

 System.Text.ASCIIEncoding encodingASCII = new System.Text.ASCIIEncoding(); System.Text.UTF8Encoding encodingUTF8 = new System.Text.UTF8Encoding(); System.Text.UnicodeEncoding encodingUNICODE = new System.Text.UnicodeEncoding(); var ascii = string.Format("{0}: {1}", encodingASCII.ToString(), encodingASCII.GetString(textBytesASCII)); var utf = string.Format("{0}: {1}", encodingUTF8.ToString(), encodingUTF8.GetString(textBytesUTF8)); var unicode = string.Format("{0}: {1}", encodingUNICODE.ToString(), encodingUNICODE.GetString(textBytesCyrillic)); 

See also: http://george2giga.com/2010/10/08/c-text-encoding-and-transcoding/ .

0
source
 var ascii = $"{new ASCIIEncoding().ToString()}: {((ASCIIEncoding)new ASCIIEncoding()).GetString(textBytesASCII)}"; var utf = $"{new UTF8Encoding().ToString()}: {((UTF8Encoding)new UTF8Encoding()).GetString(textBytesUTF8)}"; var unicode = $"{new UnicodeEncoding().ToString()}: {((UnicodeEncoding)new UnicodeEncoding()).GetString(textBytesCyrillic)}"; 
0
source

All Articles