3

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.

2
  • It's a byte array. So each element of that array is a ....? Commented Feb 6, 2014 at 11:23
  • 1
    And question is down-voted because ... ? Commented Feb 6, 2014 at 11:27

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks ! Your examples works fine. But I receive the value in String and when I try to Convert.ToInt32(hex) I got an exception: Input string was not in a correct format.
You didn't exactly say in your question that you want to convert from string... I added that to my answer.
3

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

Comments

0

On a WinCE5 system I had to pass a char-string from a C# app to a c-dll. To form up the char string in the c# code I had to cast to byte (like @fejesjoco suggested). So to form the string test_ I had byte[] name_comms_layer = new byte[] {(byte)0x74,(byte) 0x65,(byte)0x73,(byte)0x74,(byte)0x5f,(byte) 0x00} //test_ Painful but it did work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.