[英]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.