2016-01-27 61 views
1

我想一個字符串(「00812B1FA4BEA310199D6E00DD010F5402000001807」)轉換爲字節數組。 但我希望字符串的每個數字都是十六進制值。轉換十六進制字符串(字節列表)字節數組

預期的結果:

array[0] = 0x00; 

array[1] = 0x81; 

array[0] = 0x2B; 

array[0] = 0x1F; 

etc... 

我試了幾種方法。沒有給出預期的結果。最接近的人是:

private static byte[] Convert(string tt) 
{ 
    byte[] bytes2 = new byte[tt.Length]; 
    int i = 0; 
    foreach (char c in tt) 
    { 
     bytes2[i++] = (byte)((int)c - 48); 
    } 
    return bytes2; 
} 

public static byte[] ConvertHexStringToByteArray(string hexString) 
{ 

    byte[] HexAsBytes = new byte[hexString.Length/2]; 
    for (int index = 0; index < HexAsBytes.Length; index++) 
    { 
     string byteValue = hexString.Substring(index * 2, 2); 
     byte[] a = GetBytes(byteValue); 
     HexAsBytes[index] = a[0]; 
    } 
    return HexAsBytes; 
} 
+0

簡單的谷歌搜索將給你幾個解決方案,其中任何一個工作。 –

+0

對於那些正在寫簡單的谷歌搜索的人會給你解決方案...做搜索,如果它的工作發佈使用的關鍵字。自從幾個小時後,我開始使用Google搜索解決方案。 – CloudAnywhere

+0

我已經做了搜索,發現了幾場比賽,測試了它們。我也修復了你的代碼,只需要2個簡單的小修改,但是,我仍然會把它作爲一個副本投票。簡單的'byte a = System.Convert.ToByte(byteValue,16); HexAsBytes [index] = a;' –

回答

0

您可以使用Convert.ToByte到2個十六進制字符轉換爲字節。

public static byte[] HexToByteArray(string hexstring) 
{ 
    var bytes = new List<byte>(); 

    for (int i = 0; i < hexstring.Length/2; i++) 
     bytes.Add(Convert.ToByte("" + hexstring[i*2] + hexstring[i*2 + 1], 16)); 

    return bytes.ToArray(); 
} 
+0

無法編譯:出現錯誤:參數2:無法從'int'轉換爲'System.IFormatProvider' – CloudAnywhere

+0

我修正了編譯錯誤。 – TSnake41

0

在這裏找到解決方案:How do you convert Byte Array to Hexadecimal String, and vice versa? (回答爲瓦利德伊薩碼反向功能開始) 很難找到,因爲線程有36個答案。

public static byte[] HexToBytes(string hexString) 
    { 
     byte[] b = new byte[hexString.Length/2]; 
     char c; 
     for (int i = 0; i < hexString.Length/2; i++) 
     { 
      c = hexString[i * 2]; 
      b[i] = (byte)((c < 0x40 ? c - 0x30 : (c < 0x47 ? c - 0x37 : c - 0x57)) << 4); 
      c = hexString[i * 2 + 1]; 
      b[i] += (byte)(c < 0x40 ? c - 0x30 : (c < 0x47 ? c - 0x37 : c - 0x57)); 
     } 

     return b; 
    } 
相關問題