Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have following problem: I'm reading 8 bit signal from one Arduino pin and store all informatin in bool array. Now I want to convert this array to single byte in decimal. How to do this?

I've tried this:

bool ID[8] = {0, 0, 0, 0, 0, 0, 1, 1};
int recivedID = int(ID);

and

bool ID[8] = {0, 0, 0, 0, 0, 0, 1, 1};
int recivedID = ID.toInt();

non works.

share|improve this question
1  
Why save it in a bool array in the first place? You could make a byte and set each bit individually. That will be more efficient. – Paul Aug 16 at 9:16
up vote 0 down vote accepted

try with this:

int recivedID = ID[0] | (ID[1] << 1) | (ID[2] << 2) | (ID[3] << 3) | (ID[4] << 4) | (ID[5] << 5) | (ID[6] << 6) | (ID[7] << 7);

which is the same as

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

I haven't tested it though.

share|improve this answer
    
Second way is best form me, thanks :) – MrJW Aug 16 at 9:56
byte BoolArrayToByte(bool boolArray[8])
{
  byte result = 0; 

  for(int i = 0; i < 8; i++)
  {
    if(boolArray[i])
    {
      result = result | (1 << i);
    }
  }

  return result;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.