How to create byte array with your own bytes?

I have to create my own byte array e.g:

byte[] connect = new byte[] { 0x00, 0x21, 0x60, 0x1F, 0xA1, 0x07 };

This byte array works fine, but I need to change some hex code. I tried to do a lot of changes but no one work.

Int32 hex = 0xA1; 

byte[] connect = new byte[] { 0x00, 0x21, 0x60, 0x1F, 0xA1, hex};


string hex = "0xA1"; 

byte[] connect = new byte[] { 0x00, 0x21, 0x60, 0x1F, 0xA1, hex};


byte[] array = new byte[1];
array[0] = 0xA1;

byte[] connect = new byte[] { 0x00, 0x21, 0x60, 0x1F, 0xA1, array[0]};

I don't know what type of variable I must have to use to replace automatic the array values.

Answers


Cast your int to byte:

Int32 hex = 0xA1; 
byte[] connect = new byte[] { 0x00, 0x21, 0x60, 0x1F, 0xA1, (byte)hex};

Or define it as byte to begin with:

byte hex = 0xA1; 
byte[] connect = new byte[] { 0x00, 0x21, 0x60, 0x1F, 0xA1, hex};

String to byte conversion:

static byte hexstr2byte(string s)
{
    if (!s.StartsWith("0x") || s.Length != 4)
        throw new FormatException();
    return byte.Parse(s.Substring(2), System.Globalization.NumberStyles.HexNumber);
}

As you can see, .NET formatting supports hexa digits, but not the "0x" prefix. It would be easier to omit that part altogether, but your question isn't exactly clear about that.


Declare it like "byte hex = 0xA1" maybe?


Need Your Help

Invalid file Save Error Python

python python-3.x tkinter savefiledialog

I'm trying to write a script that allows a user to create a folder with any name they want, and then create a file with any name they want. Once they do they, the program asks them for 3 names and ...

Does WxPack works with GCC 4.5/4.6 Series

wxwidgets

Hello I have installed TDM-GCC compiler suite for windows. Do i need to install MinGW 5.1.3 gcc 3.4.5 (candidate) to make wxpack work as said here