簡體   English   中英

C# 將十六進制值轉換為 UTF8 和 ASCII

[英]C# convert hexadecimal value in to UTF8 and ASCII

我正在嘗試將字符串中的十六進制值轉換為 ASCII 值和 UTF8 值。 但是當我執行以下代碼時,它會打印出我作為輸入提供的相同十六進制值

string hexString = "68656c6c6f2c206d79206e616d6520697320796f752e";
System.Text.UTF8Encoding  encoding=new System.Text.UTF8Encoding();
byte[] dBytes = encoding.GetBytes(hexString);

//To get ASCII value of the hex string.
string ASCIIresult = System.Text.Encoding.ASCII.GetString(dBytes);
MessageBox.Show(ASCIIresult, "Showing value in ASCII");

//To get the UTF8 value of the hex string
string utf8result = System.Text.Encoding.UTF8.GetString(dBytes);
MessageBox.Show(utf8result, "Showing value in UTF8");

由於您正在命名一個變量hexString ,我假設該值已被編碼為十六進制格式。

這意味着以下內容將不起作用:

string hexString = "68656c6c6f2c206d79206e616d6520697320796f752e";
System.Text.UTF8Encoding  encoding=new System.Text.UTF8Encoding();
byte[] dBytes = encoding.GetBytes(hexString);

這是因為您將已編碼的字符串視為純 UTF8 文本。

您可能缺少將十六進制編碼字符串轉換為字節數組的步驟。

您可以使用顯示此功能的此 SO 帖子來執行此操作:

public static byte[] StringToByteArray(String hex)
{
  int NumberChars = hex.Length/2;
  byte[] bytes = new byte[NumberChars];
  using (var sr = new StringReader(hex))
  {
    for (int i = 0; i < NumberChars; i++)
      bytes[i] = 
        Convert.ToByte(new string(new char[2]{(char)sr.Read(), (char)sr.Read()}), 16);
  }
  return bytes;
}

所以,最終的結果是這樣的:

byte[] dBytes = StringToByteArray(hexString);

//To get ASCII value of the hex string.
string ASCIIresult = System.Text.Encoding.ASCII.GetString(dBytes);
MessageBox.Show(ASCIIresult, "Showing value in ASCII");

//To get the UTF8 value of the hex string
string utf8result = System.Text.Encoding.UTF8.GetString(dBytes);
MessageBox.Show(utf8result, "Showing value in UTF8");

您應該首先將十六進制字符串轉換為字節數組:

byte[] dBytes = Enumerable.Range(0, hexString.Length)
                 .Where(x => x % 2 == 0)
                 .Select(x => Convert.ToByte(hexString.Substring(x, 2), 16))
                 .ToArray();

我用這個方法來轉換任何

public static string FromHex (string h) //Put your sequence of hex to convert to string.
{
    if (h.Length % 2 != 0) 
        throw new ArgumentException("The string " + nameof(h) + " is not a valid Hex.", nameof(h));
    char[] CharFromHex = new char[h.Length / 2];
    int j = 0;
    for (int i = 0; i < h.Length; i += 2)
    {
        string hexSubStr = h.Substring(i, 2);
        CharFromHex[j] = (char)Convert.ToInt32(hexSubStr, 16);
        j += 1;
    }
    StringBuilder str = new StringBuilder();
    str.Append(CharFromHex);
    return str.ToString();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM