C++ 如何在Arduino/C/C+中将布尔数组转换为字节+;?
我是arduino编程(c/c+)的新手。并希望将带有布尔值的数组转换为类似字节的数组。这里的布尔人代表一个按钮C++ 如何在Arduino/C/C+中将布尔数组转换为字节+;?,c++,arrays,arduino,C++,Arrays,Arduino,我是arduino编程(c/c+)的新手。并希望将带有布尔值的数组转换为类似字节的数组。这里的布尔人代表一个按钮 bool array[] = {0,1,1,0}; // needs to convert to 0b0110 // bool array[] = {1,0,0,0}; // needs to convert to 0b1000 // bool array[] = {true,true,false,true}; // needs to convert to 0b1101 void
bool array[] = {0,1,1,0}; // needs to convert to 0b0110
// bool array[] = {1,0,0,0}; // needs to convert to 0b1000
// bool array[] = {true,true,false,true}; // needs to convert to 0b1101
void setup(){
byte b = convert(array); // 0b0110
}
byte convert(bool array[]){
byte b = 0b + 0 + 1 + 1 + 0; // <- wrong stuff here :(
return b;
}
bool数组[]={0,1,1,0};//需要转换为0b0110
//布尔数组[]={1,0,0,0};//需要转换为0b1000
//布尔数组[]={true,true,false,true};//需要转换为0b1101
无效设置(){
字节b=转换(数组);//0b0110
}
字节转换(布尔数组[]){
字节b=0b+0+1+1+0;//我现在无法重写您的所有代码,但我可以列出一个基本算法。我想它会对您有所帮助
你需要一些东西,要么在循环中,要么是硬编码的(如果你真的只有四位的话)。为了简单起见,我将调用你的数组a
,我将只对计算进行硬编码,这样它就非常清晰了
如果以位为单位考虑数组的条目,则如下所示:
eights fours twos ones
{ 0 , 1 , 1 , 0 }
shift 3 shift 2 shift 1 no shift
uint8_t b = (a[0] << 3) + (a[1] << 2) + (a[2] << 1) + a[3];
so -> no eights one four one two no ones
6 = 0 + 4 + 1 + 0
uint8_t b = (
(a[0] ? 1 << 3 : 0) +
(a[1] ? 1 << 2 : 0) +
(a[2] ? 1 << 1 : 0) +
(a[3] ? 1 : 0 )
);
使用左移位运算符