expressing a statement most compact method

Hi
Is there a more compact method of expressing this statement below, I'm using it to shift the bits 1 position to the left ? bitIndex = bitIndex <<1;

// sample of code to reading data from a MT8870 DTMF ic

  const byte pins[] = {11,10,9,8};
  byte bitIndex = 1;
  byte val = 0;
  byte data = 0;
  //read the 4 data pins from MT8870
  for (byte i=0; i<4; i++)
    {
      val = digitalRead(pins[i]); 
      if (val)
        data |= bitIndex;  
      bitIndex = bitIndex << 1; //shift bits left   
    }

Thanks Don

Since HIGH is 1 and LOW is 0:

 const byte pins[] = {11,10,9,8};
  byte val = 0;
for (byte i=0; i<4; i++)
    {
      val |= digitalRead(pins[i]) << i; 
    }

Are you trying to make this specific statement more compact?

bitIndex = bitIndex << 1; //shift bits left

If so, a slightly more compact form would be:

bitIndex <<= 1; //shift bits left

If you're trying to make the overall for loop more compact then you could replace it with something like this:

for (byte i=0; i<sizeof(pins); i++)
{
    bitWrite(data, i, digitalRead(pins[i])); 
}

Thanks John, that's really simply. I struggle the most simple ways of coding my solutions to the task at hand

I'm looking to build a binary number of the input pins I listed.

Thanks Peter H too

Multiplying by 2 has exactly the same effect as shifting the bits one place left.

On the Arduino Uno this can be done with a single read:

  data = PINB & 15;

But that's just because pins 11-8 happen to be PB3-0.

Didn't think of that one I just happen to pick those pins.

Is there a problem solving in c book anyone can recommend to me so I
Can get more experience solving these type of problems. I feel like Im doing things the hard way kinda step by step. It's very interesting how different people code the same task.

Don

const uint8_t pins[] = { 11, 10,  9,  8 };
for ( size_t i = sizeof(pins); i--; )
{
    val |= digitalRead(pins[i]) << 1; 
}

lloyddean:

const uint8_t pins[] = { 11, 10,  9,  8 };

for ( size_t i = sizeof(pins); i--; )
{
    val |= digitalRead(pins[i]) << 1;
}

That's not going to work. If you unroll the loop you get:

   val |= digitalRead(pins[3]) << 1;
   val |= digitalRead(pins[2]) << 1;
   val |= digitalRead(pins[1]) << 1;
   val |= digitalRead(pins[0]) << 1;

If all for pins are HIGH that is equivalent to:

   val |= 2;
   val |= 2;
   val |= 2;
   val |= 2;

A minor sidenote: My experince is that the compiler is not all that stupid - it usually does not matter how "compact" you write the code, it ends up with the same generated code. So unless one is having a timecritical code, write things the obvious human friendly way. (Reading tones from DTMF signal is probably not going to break if the loop takes 10us or 20us to do)

Yes I know by it got posed prematurely by accident then I lost my internet connection for the evening and I was unable to remove, correct it.

My apologies