简体   繁体   English

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

[英]How do i convert an array with booleans to a byte in Arduino/C/C++?

I'm new in arduino programming (c/c+).我是 arduino 编程 (c/c+) 的新手。 And would like to convert a array with bool's to an byte like.并且想将带有布尔值的数组转换为类似字节的数组。 The booleans repreprents a buttons here.布尔值在这里表示一个按钮。

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

I can't rewrite all your code right now, but I can lay out a basic algorithm.我现在不能重写你所有的代码,但我可以列出一个基本的算法。 I think it'll help you.我想它会帮助你。

You need something, either in a loop or hardcoded (if you really only have four bits).你需要一些东西,要么是循环的,要么是硬编码的(如果你真的只有四位的话)。 For brevity, I'm going to call your array a and I'll just hardcode the calculation so it's super-clear.为简洁起见,我将调用您的数组a并且我将对计算进行硬编码,因此它非常清晰。

If you think of the entries of your array in bits, it's like this:如果您以位为单位考虑数组的条目,则如下所示:

 eights  fours  twos  ones
{   0   ,  1   , 1   , 0 }

You get these values by using the left-shift operator << which doubles the value for each shift.您可以使用左移运算符<<获得这些值,该运算符将每次移位的值加倍。

So with the leftmost member of your array as the most significant bit, you do it like this:因此,将数组的最左边成员作为最重要的位,您可以这样做:

             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

Do you see the pattern?你看到图案了吗? Each less significant bit is shifted by one LESS to the left, halving its total value.每个较低有效位向左移动一个 LESS,使其总值减半。 The sum of these values is your byte value ( uint8_t ).这些值的总和是您的字节值( uint8_t )。

There are other notations which have the same effect, but this one is the easiest to understand.还有其他符号具有相同的效果,但这个是最容易理解的。

Now to the booleans.现在到布尔值。 You could use the ternary operator and test each element, something like this:您可以使用三元运算符并测试每个元素,如下所示:

uint8_t b = (
    (a[0] ? 1 << 3 : 0) + 
    (a[1] ? 1 << 2 : 0) + 
    (a[2] ? 1 << 1 : 0) + 
    (a[3] ? 1 : 0 )
    );

Once you see this pattern, you can do all sorts of cool bitwise constructions with it.一旦你看到这个模式,你就可以用它做各种很酷的按位构造。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM