stack questions
stack questions

Reputation: 982

Convert array values of 1's and 0's to binary

In Arduino IDE, I am placing all of input values to an array like so:

int eOb1 = digitalRead(PrOb1);
int eLoop = digitalRead(PrLoop);
int eOb2 = digitalRead(PrOb2);

InputValues[0] = eOb1;
InputValues[1] = eLoop;
InputValues[2] = eOb2;
InputValues[3] = 0;
InputValues[4] = 0;
InputValues[5] = 0;
InputValues[6] = 0;
InputValues[7] = 0;

I would like to convert it to a byte array like so: 00000111.
Can you show me please. I tried using a for Loop to iterate through the values but it doesn't work.

char bin[8];
for(int i = 0; i < 8; ++i) {
   bin &= InputValues[i];
}

Upvotes: 2

Views: 727

Answers (1)

Ajay Brahmakshatriya
Ajay Brahmakshatriya

Reputation: 9203

If I understand your requirement correctly, you have an array of individual bits and you need to convert it into a byte that has the corresponding bits.

So to start, you should declare bin to be of type unsigned char instead of char[8]. char[8] means an array of 8 bytes, whereas you only need a single byte.

Then you need to initialize it to 0. (This is important since |= needs the variable to have some defined value).

unsigned char bin;

Now, unsigned char is guaranteed to have 1 byte but not 8 bits. So you should use something like uint8_t IF it is available.

Finally you can set the appropriate bits in bin as -

for(int i = 0; i < 8; ++i) {
    bin |= (InputValues[i] << i);
}

There are two things I have changed.

  1. I used |= instead of &=. This is the bitwise OR operator. You need to use OR because it only sets the correct bits in the LHS and leaves other bits untouched. An AND won't necessarily set that bit and will also mask away (set to 0), the other bits.
  2. Shifted the bit in the array to the corresponding position using << i.

Upvotes: 5

Related Questions