[英]How to present a character Unicode with 5 digit (Hex) with c# language
[英]Hex string to unicode (Chinese or other language) C#
我可以使用UTF8进行转换,但是当我测试Unicode时,无论我是否设置了错误,都会丢失一些字符
请给我一些建议
Chinese =“对我很有帮助”丢失的显示:“?我很有帮?”
static void Main(string[] args)
{
String hex2 = "F95B1162885F09672E5EA9522100";
String temp3 = Trans2(hex2);
Console.WriteLine(temp3);
Console.ReadLine();
}
public static string Trans(String input)
{
string temp1 = ConvertHexToString(input, System.Text.Encoding.UTF8);
return temp1;
}
private static string ConvertHexToString(String hexInput, System.Text.Encoding encoding)
{
int numberChars = hexInput.Length;
byte[] bytes = new byte[numberChars / 2];
for (int i = 0; i < numberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(hexInput.Substring(i, 2), 16);
}
return encoding.GetString(bytes);
}
我已经测试了您的代码,但无法复制您的问题。 在我的环境中一切正常。 但是,我确实同意@ grek40关于控制台编码,或者研究您的控制台中使用的字体-它能够显示这些字符吗?
我的测试代码在下面的GUI应用程序上,您可以尝试一下:
private static string ConvertHexToString(String hexInput, System.Text.Encoding encoding) {
int numberChars = hexInput.Length;
byte[] bytes = new byte[numberChars / 2];
for (int i = 0; i < numberChars; i += 2) {
bytes[i / 2] = Convert.ToByte(hexInput.Substring(i, 2), 16);
}
return encoding.GetString(bytes);
}
private static string ConvertStringToHex(String strInput, System.Text.Encoding encoding) {
return BitConverter.ToString(encoding.GetBytes(strInput)).Replace("-", String.Empty);
}
private void button1_Click(object sender, EventArgs e) {
string strTest = "对我很有帮助!";
Debug.Print(strTest);
string hex;
hex = ConvertStringToHex(strTest, Encoding.UTF8);
Debug.Print(hex);
Debug.Print(ConvertHexToString(hex, Encoding.UTF8));
hex = ConvertStringToHex(strTest, Encoding.Unicode);
Debug.Print(hex);
Debug.Print(ConvertHexToString(hex, Encoding.Unicode));
Debug.Print(ConvertHexToString("F95B1162885F09672E5EA9522100", Encoding.Unicode));
}
结果如下:
对我很有帮助!
E5AFB9E68891E5BE88E69C89E5B8AEE58AA921
对我很有帮助!
F95B1162885F09672E5EA9522100
对我很有帮助!
对我很有帮助!
显然,示例代码中的十六进制字符串为Unicode格式。
PS:如果您从文件中读取输入,则需要考虑文件是否使用大/小端编码,以及是否使用BOM。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.