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 int
s to bytes and put them into my byte array?
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;
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 };
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.