简体   繁体   English

将二进制信号转换为整数

[英]Convert binary signal to int number

I'm trying to convert the input of the GPIOs of a raspberry pi to a int. 我正在尝试将树莓派的GPIO的输入转换为int。 So I have five digital inputs and want to read the inputs. 因此,我有五个数字输入,并且想读取这些输入。 Once i got the values I store them in an array. 一旦获得值,就将它们存储在数组中。 The next thing would be to convert the content of the array to a int number. 接下来的事情是将数组的内容转换为一个int数。

So here's my code: 所以这是我的代码:

int a = digitalRead(PIN_16);
int b = digitalRead(PIN_18);
int c = digitalRead(PIN_22);
int d = digitalRead(PIN_24);
int e = digitalRead(PIN_26);

int array[5];

array[0]=a;
array[1]=b;
array[2]=c;
array[3]=d;
array[4]=e;

To convert the content of the array to a number I would youse if conditions to see if the first input is 1 or 0. If its 1 I a 1, else 0. And so on ... . 要将数组的内容转换为数字,请根据条件查看第一个输入是否为1或0。如果其1为1,否则为0。依此类推。

My question now is if there's a more elegant way to do this. 我现在的问题是,是否有更优雅的方法可以做到这一点。

Just "shift" bits into the appropriate positions in the number: 只需将“位”“移”到数字中的适当位置即可:

unsigned int number = 0;
for (int i=0; i<5; i++)
{
    number |= a[i] << i;
} 

This will work in case digitalRead is returning 0 or 1 only. 万一digitalRead只返回01这将起作用。 In case it returns 0 or a non-zero values we will need to check it against zero instead: 如果它返回0non-zero值,我们将需要对照零进行检查:

unsigned int number = 0;
for (int i=0; i<5; i++)
{
    number |= (a[i] != 0) << i;  //  (a[i] != 0) will have a value of `1` for any non-zero `a[i]`
} 

or even more idiomatic trick: 或更惯用的技巧:

number |= !!a[i] << i;  

This is a double logical negation. 这是双重逻辑否定。 The first one will turn any non-zero into 0 , the second will turn the 0 into 1 . 第一个将非零值转换为0 ,第二个将0转换为1

您可以通过按位操作来做到这一点:

result = array[4]<<4 | array[3]<<3 | array[2]<<2 | array[1]<<1 | array[0]

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

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