Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert from Hex to Unicode?

Tags:

c#

unicode

My application receives Hex values from client and converts back to character which is usually chinese character. But I can't implement this properly. As per my current programme it can convert "e5a682e4bd95313233" to "如何123" but I am actually receiving "59824F55003100320033" from the client side for the same Chinese character "如何123" and my programme unable to convert back into string. Please help me on this.

Here is my current code:

        byte[] uniMsg = null;
        string msg = "59824F55003100320033";
        uniMsg = StringToByteArray(msg.ToUpper());
        msg = System.Text.Encoding.UTF8.GetString(uniMsg);


        public static byte[] StringToByteArray(String hex)
        {
          hex = hex.Replace("-", "");
          byte[] raw = new byte[hex.Length / 2];
          for (int i = 0; i < raw.Length; i++)
          {
             raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
          }
          return raw;
        }

Appreciate any help on this. Thanks.

Solution:

updated

  msg = System.Text.Encoding.UTF8.GetString(uniMsg);

to

 msg  = System.Text.Encoding.BigEndianUnicode.GetString(uniMsg)

Thanks to @CodesInChaos for suggesting the encoding type.

like image 704
barsan Avatar asked Dec 01 '25 14:12

barsan


1 Answers

It doesn't seem to be encoded in UTF8. Note the 00 31 00 32 00 33 part. In UTF8, it'd be just 31 32 33. I think the hexstring is in UTF16 BE, because it's exactly 2 bytes per character and they are 00-padded. Decode your byte array as UTF16, you will get a string. Then you can use it as string, or reconvert it to any other encoding you need.

like image 127
quetzalcoatl Avatar answered Dec 04 '25 04:12

quetzalcoatl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!