2010-10-19 177 views
3

目标是获得一个字节[16],其中第一个元素是十六进制值55,第二个元素是十六进制值AA。和其他14是十六进制值0需要设置一个字节[]

我试图

byte[] outStream = System.Text.Encoding.UTF8.GetBytes("55 AA 00 00 00 00 00 00 00 00 00 00 00 00 00 00"); 

但这填充字节[]使用ASCII值,而不是十六进制值。

我试图

byte[] outStream = new byte[16]; 
    outStream[0] = byte.Parse("55"); 
    outStream[1] = byte.Parse("AA"); 
    for(int i=2; i<16; i++) 
    { 
    outStream[i] = byte.Parse("00"); 
    } 

但这也不管用。它不会给出十六进制值,而是AA上崩溃的整数值,因为它不是可分析的int。

任何帮助,将不胜感激。

+1

更正:您的第一条语句填充'的byte []'与** UTF-8 **值,而不是ASCII值,因为你使用了UTF-8编码。 – Aaronaught 2010-10-19 21:08:59

回答

2

您可以使用:byte.Parse(hex_byte_string, System.Globalization.NumberStyles.HexNumber);
或者你也可以使用:Convert.ToByte(hex_byte_string, 16);

public static byte[] ToByteArray(String HexString) 
{ 
    string hex_no_spaces = HexString.Replace(" ",""); 
    int NumberChars = hex_no_spaces.Length; 
    byte[] bytes = new byte[NumberChars/2]; 
    for (int i = 0; i < NumberChars; i+=2) 
    { 
     bytes[i/2] = byte.Parse(hex_no_spaces.Substring(i, 2), System.Globalization.NumberStyles.HexNumber); 
    } 
    return bytes; 
} 

而且使用这样的:

byte[] bytez = ToByteArray("55 AA 00 00 00 00 00 00 00 00 00 00 00 00 00 00"); 
+0

这工作完美。谢谢。 – 2010-10-20 13:54:45

12

您可以通过在前面把它写在C#中文字十六进制整数用0x:

byte[] result = new byte[16]; 
result[0] = 0x55; 
result[1] = 0xaa; 

默认情况下,字节数组填充0x00,因此您只需设置前两个元素。

或者,你可以使用数组初始化器的语法:

byte[] result = new byte[] { 0x55, 0xaa, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; 
2
byte[] result = { 0x55, 0xaa, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; 
相关问题