项目遇到BLE蓝牙用byte数组传值过来控制led灯的RGB颜色问题,使用int值的话0xff0000这种格式就可以解决;使用byte[]{ff,00,00}转化成int的话,
1、首先我们想到位移"<<",">>",一个byte是8bit所以每次需要移动8位;
2、但直接位移的话byte是有符号的,移到高位后还是有符号的。所以我们需要先去符号:
public static int toUnsignedInt(byte x) {
return ((int) x) & 0xff;
}
最终
byte[] bytes = new byte[]{(byte) 0xf1,(byte) 0xfb, (byte) 0xa1};
Byte byteR = bytes[0];
Byte byteG = bytes[1];
Byte byteB = bytes[2];
int colorRGB = ((toUnsignedInt(byteR))<< 16)+ ((toUnsignedInt(byteG))<<8) + (toUnsignedInt(byteB));