简体   繁体   中英

Convert binary signal to int number

I'm trying to convert the input of the GPIOs of a raspberry pi to a 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.

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 ... .

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. In case it returns 0 or a non-zero values we will need to check it against zero instead:

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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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