How to convert emojis from to unicode in Xamarin.f

2019-08-18 15:27发布

问题:

I have Xamarin.Forms project. I have textbox in that and have a button which get text from textbox and pass it to API to store. Now the point is when user select any emojis from keyboard, I want to get unicode character of the emojis. Currently I am getting emojis it self when I check Text property of it.

I want to get Unicode rather emoji as given in NewTextValue from Text property.

This post is same but I don't understand how the guy has managed. POST

Please suggest.

After some google, I have tried with following.

string res = BitConverter.ToString(Encoding.BigEndianUnicode.GetBytes(str)).Replace("-", "");

This is result res = D83DDE00 I don't know above code is unicode or not.

How can I convert back to original emoji or is there any other way to convert in unicode?

回答1:

We need to manually convert it back. Insert "-" every two characters:

var convertStr = string.Join("-", Regex.Matches(res, @"..").Cast<Match>().ToList());
String[] tempArr = convertStr.Split('-');
byte[] decBytes = new byte[tempArr.Length];
for (int i = 0; i < tempArr.Length; i++)
{
    decBytes[i] = Convert.ToByte(tempArr[i], 16);
}
String str = Encoding.BigEndianUnicode.GetString(decBytes);

Moreover in my test, Encoding.UTF32.GetBytes() may be closer to emoji code. You can test it with \U0001F600, this is a smile image. After converting with utf32, the bytes just change its order.