Byte must be configured []

The goal is to get a byte [16], where the first element is the hexadecimal value 55, and the second element is the hexadecimal value AA. And the remaining 14 are the hexadecimal value of 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 it fills byte [] with ascii values, not hexadecimal 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 it doesn’t work either. It does not give hexadecimal values, but integer values ​​that fail on AA, since it is not a syntax index.

Any help would be appreciated.

+3
source share
3 answers

You can write a hexadecimal integer literal in C # whose prefix is ​​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 };
+12

: 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");
+2
byte[] result = { 0x55, 0xaa, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+2
source

Source: https://habr.com/ru/post/1770403/


All Articles