2

I'm sending five bytes to an Arduino:

byte[] { 0xF1, byte1, byte2, byte3, 0x33 }

The values of byte1, byte2 and byte3 are dynamic. The first and last bytes are always the same.

Byte values are from 0 to 255.

How can I simply convert ints to bytes and put them into my byte array?

3 Answers 3

1

To get array of bytes from int use:

    byte[] intAsArrayOfBytes = BitConverter.GetBytes(yourInt);

then you can copy values to your array

   byte[] { 0xF1, intAsArrayOfBytes[0], intAsArrayOfBytes[1], intAsArrayOfBytes[3], 0x33 }

or if you need just convert int type into byte type and you know that variable between 0..255 use:

   byte byte1 = (byte) int1;
   byte byte2 = (byte) int2;
   byte byte3 = (byte) int3;
Sign up to request clarification or add additional context in comments.

Comments

0

If you are sure that your values won't exceed the byte range [0, 255], you can simply cast them:

byte[] b = { 0xF1, (byte)byte1, (byte)byte2, (byte)byte3, 0x33 }

In alternative you can use Convert.ToByte, which throws an OverflowException if values are less than 0 or greater than 255.

Comments

0

Assuming the ints are between 0 and 255, use Convert.ToByte(). For example:

int byte1;
int byte2;
int byte3;
byte[] bytes = new byte[]{ 0xF1, Convert.ToByte(byte1), 
    Convert.ToByte(byte2), Convert.ToByte(byte3), 0x33 };

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.