c++ - 如何在Arduino/C/C++中将带有 bool 值的数组转换为字节?

标签 c++ arrays arduino

我是arduino编程(c / c +)的新手。并希望将带有 bool(boolean) 值的数组转换为字节。 bool(boolean) 值在这里表示一个按钮。

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

最佳答案

我现在无法重写所有代码,但是可以布局一个基本算法。我想会帮你的。
您需要循环或硬编码(如果您实际上只有四个位)的内容。为简便起见,我将调用您的数组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
你看到图案了吗?每个较低有效位向左移动一个LESS,将其总值减半。这些值的总和是您的字节值(uint8_t)。
还有其他具有相同效果的符号,但是这一符号最容易理解。
现在到 bool(boolean) 。您可以使用三元运算符并测试每个元素,如下所示:
uint8_t b = (
    (a[0] ? 1 << 3 : 0) + 
    (a[1] ? 1 << 2 : 0) + 
    (a[2] ? 1 << 1 : 0) + 
    (a[3] ? 1 : 0 )
    );
一旦看到了这种模式,就可以使用它进行各种酷炫的按位构造。

关于c++ - 如何在Arduino/C/C++中将带有 bool 值的数组转换为字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63157172/

相关文章:

c++ - 优化昂贵函数的调用次数

c++ - visual studio c++ 2010 express 中的程序错误

arrays - 在 VBA 中定义数组设置步长值

ios - 使用本地数组数据、Swift、UITableView 更新 Parse 数组

c++ - { 错误之前的预期类名

database - Arduino 从 SD 卡读取数据库文件

c++ - 如何在 C++ 中创建文件映射?

c++ - 如何从远程线程 DestroyWindow?

java - 使用 ArrayList 而不是数组来避免使用普通的 for 循环

mysql - 使用 Arduino IDE 借助变量从节点 MCU 发送数据