SOLVED: Which bit changed?

I'm using direct port reading in a project, and I need to know if a pin status changed. So the firs step was to compare a status before and after of the PORT value and I get to a binary number that gives me a 1 where the bit has changed. Now I got stuck at trying to get an "elegant" solution to a function that will work like this:

  • If input is 0001 the result will be 1
  • If input is 0100 the result will be 3

And so on...

Only one bit will be high at the time.
Is there a bitwise operator that will give me this kind of result?
Regards

If input is 1 the result will be 1
If input is 4 the result will be 3

OK, I'm lost.

Only one bit will be high at the time.
Is there a bitwise operator that will give me this kind of result?

With only two data points, it's hard to tell you what you need to do.

XOR.

The xor (^) operator will return a value which has the bits set in it that have changed between two variables.

Store the state, and compare the previous state to the current state with xor:

static unsigned char previousState;
unsigned char currentState;
unsigned char changed;

changed = previousState ^ currentState;
previousState = currentState;

Some examples:

Previous Current Compare
01101001 01101011 00000010
01101001 01101000 00000001
01101001 01111001 00010000

... and so on.

If you then want to know if the bit is on or off, you can and the result with the port value to give a masked port value.

You probably mean something like this:

  unsigned char port = 0b10; // 
 
  int pos = 0;
  int i=0;
  for (i=0; i<8; i++) {
    if ((port >> i)&0x1) {
      pos = i+1;
      break;
    }
  }
 // pos == 2 here

Your solution looks great Pekaa! Thanks