Reputation: 2491
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.
Upvotes: 3
Views: 2634
Reputation: 33566
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.
Upvotes: 3