tags:

views:

74

answers:

3

The goal is to get a byte[16] where the first element is hex value 55 and the second element is hex value AA. And the other 14 are hex value 0.

I tried

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

but this fills the byte[] with the ascii values, not the hex values.

I tried

  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");
  }

but this doesn't work either. It doesn't give the hex values, but rather the integer values which crashes on the AA since it is not a parsable int.

Any help would be appreciated.

+2  A: 

You can use: byte.Parse(hex_byte_string, System.Globalization.NumberStyles.HexNumber);
Or you could also use: 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;
}

And use it like this:

byte[] bytez = ToByteArray("55 AA 00 00 00 00 00 00 00 00 00 00 00 00 00 00");
SwDevMan81
This works perfectly. Thanks.
Dan Hass
+12  A: 

You can write a hexadecimal integer literal in C# by prefixing it with 0x:

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

Byte arrays are filled with 0x00 by default, so you just have to set the first two elements.

Alternatively, you can use array initialiser syntax:

byte[] result = new byte[] { 0x55, 0xaa, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
dtb
+2  A: 
byte[] result = { 0x55, 0xaa, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
akonsu