我送五个字节到一个Arduino:如何转换INT对字节数组有两个固定值
byte[] { 0xF1, byte1, byte2, byte3, 0x33 }
的byte1
,byte2
和byte3
的值是动态的。第一个和最后一个字节总是相同的。
字节值从0到255
我怎么能简单地转换int
s到字节并把它们放到我的字节数组?
我送五个字节到一个Arduino:如何转换INT对字节数组有两个固定值
byte[] { 0xF1, byte1, byte2, byte3, 0x33 }
的byte1
,byte2
和byte3
的值是动态的。第一个和最后一个字节总是相同的。
字节值从0到255
我怎么能简单地转换int
s到字节并把它们放到我的字节数组?
如果你确信你的价值不会超过字节范围[0, 255]
,你可以简单地丢掉。
byte[] b = { 0xF1, (byte)byte1, (byte)byte2, (byte)byte3, 0x33 }
在替代你可以使用Convert.ToByte
,它抛出一个OverflowException
如果值小于0或者更大比255.
假设整数在0到255之间,请使用。例如:
int byte1;
int byte2;
int byte3;
byte[] bytes = new byte[]{ 0xF1, Convert.ToByte(byte1),
Convert.ToByte(byte2), Convert.ToByte(byte3), 0x33 };
由Int使用得到的字节数组:
byte[] intAsArrayOfBytes = BitConverter.GetBytes(yourInt);
那么你就可以值复制到阵列
byte[] { 0xF1, intAsArrayOfBytes[0], intAsArrayOfBytes[1], intAsArrayOfBytes[3], 0x33 }
,或者如果你只需要转换整型成字节类型,你知道0..255之间的变量使用:
byte byte1 = (byte) int1;
byte byte2 = (byte) int2;
byte byte3 = (byte) int3;