2016-01-27 58 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; 
    } 
相关问题