2012-09-06 38 views
2

我送五個字節到一個Arduino:如何轉換INT對字節數組有兩個固定值

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

byte1byte2byte3的值是動態的。第一個和最後一個字節總是相同的。

字節值從0到255

我怎麼能簡單地轉換int s到字節並把它們放到我的字節數組?

回答

0

如果你確信你的價值不會超過字節範圍[0, 255],你可以簡單地丟掉。

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

在替代你可以使用Convert.ToByte,它拋出一個OverflowException如果值小於0或者更大比255.

0

假設整數在0到255之間,請使用。例如:

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

由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;