我想一個字符串(「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;
}
簡單的谷歌搜索將給你幾個解決方案,其中任何一個工作。 –
對於那些正在寫簡單的谷歌搜索的人會給你解決方案...做搜索,如果它的工作發佈使用的關鍵字。自從幾個小時後,我開始使用Google搜索解決方案。 – CloudAnywhere
我已經做了搜索,發現了幾場比賽,測試了它們。我也修復了你的代碼,只需要2個簡單的小修改,但是,我仍然會把它作爲一個副本投票。簡單的'byte a = System.Convert.ToByte(byteValue,16); HexAsBytes [index] = a;' –