How to convert from Hex to Unicode?

My application gets Hex values ​​from the client and converts back to a character, which is usually a Chinese character. But I can't seem to implement it correctly. According to my current program, it can convert "e5a682e4bd95313233" to "如何 123", but I actually get "59824F55003100320033" from the client side for the same Chinese character "如何 123" and my program cannot convert back to string. Please help me with 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. Thank.

Decision:

updated

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

      

to

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

      

Thanks to @CodesInChaos for specifying the encoding type.

+3


source to share


1 answer


It is not encoded in UTF8. Pay attention to the part 00 31 00 32 00 33

. In UTF8 it will be easy 31 32 33

. I think the hexstring is in UTF16 BE because it is exactly 2 bytes per character and they are 00-padded. Decode the byte array as UTF16, you will get a string. Then you can use it as a string or convert it to any other encoding.



+3


source







All Articles