16 Bit comparison

Hello!

Sorry for the Google translation, but my English is not that good to be able to describe my problem.

I am a strong beginner in arduino.

I would like to compare 16 bits, as quickly as possible in groups of 2 - 4 - 2 - 4 - 4, and find out in which group a change occurred.
Example:
new data - 10 0010 11 0000 1010
old data - 00 0010 11 0000 1010

here, bit 15 has changed from 1 to 0... I want to find this change simply and quickly and get the number of the changed bit, in this case 15.

I don't know how slow and system-intensive the "for - if" method would be on an Arduino 328.
Actually, this is all the processor would deal with, excluding 1 timer and 1 external interrupt.

Thank you all very much for your help!
I wish you a nice day!

The binary XOR operation give you a binary with only bits set, that different between new and old data:

uint16_t old_data = 0b0000101100001010;
uint16_t new_data = 0b1000101100001010;

uint16_t diff = old_data ^ new_data;

the diff will be 0b1000000000000000

Now you can easily test which bits are set

1 Like

uint16_t old_data = 0b0000101100001010;
uint16_t new_data = 0b1000101100001010;

uint16_t diff = old_data ^ new_data;
bool Diff1 = (diff & B1111) > 0;
diff = diff >> 4;
bool Diff2 = (diff & B1111) > 0;
diff = diff >> 4;
bool Diff3 = (diff & B11) > 0;
diff = diff >> 2;
bool Diff4 = (diff & B1111) > 0;
diff = diff >> 4;
bool Diff5 = (diff & B11) > 0;

Hello!

This is a very good solution, I tested it, it's fast, and it's not a "for - if" procedure consisting of 32 operation units.
I still have a lot to improve...
Because of object-oriented languages, many of us - like me - forget to learn the operations with BITs, even though everything started from there...from that became the ASM language and the rest.
I'm going back to the "school desk" - you have to learn these things! :slight_smile:

Thank you very much for your help!
I wish you a nice day!