comparing two arrays in a loop

Hi,

I have two byte arrays.

unsigned char response = { 0x56, 0x00, 0x36, 0x01 };
unsigned char expectedResponse = { 0x56, 0x00, 0x36, 0x01 };

How can I compare that these match by checking each element one at a time in a loop?

memcmp

If that's too complicated, just cast them to be "unsigned long"s and compare them directly.

Thanks, I'd like to use the loop method. Could you demonstrate how to do it? Also why is it necessary to cast them?

Also why is it necessary to cast them?

Because the two arrays are not "unsigned long"s.
But they occupy the same number of bytes.

Thanks, I'd like to use the loop method.

You can be pretty sure that "memcmp" uses a loop.

Could you demonstrate how to do it?

Just write a for loop that loops four times.
If the two items being compared are unequal, break out of the for loop.

Hi,

Thanks for explaining, I wrote this app, it checks each element one by one. How could I make it just print out if all the elements are the same, yes/no?

I can’t use the memcmp on the mcu that I’m using.

Thanks

#include <stdio.h>
void compare(unsigned char a[], unsigned char b[])
{
int i,j;
for ( i=0;i<4;++i)
{
    for ( j=0;j<4;++j)
    {
        if (a[i] == b[j])
        {
            printf("same\n");
        }
    }
}
}

int main()
{ 

unsigned char arr1[] = { 0x56, 0x00, 0x24, 0x03, 0x01, 0x2A };
unsigned char arr2[] = { 0x56, 0x00, 0x24, 0x03, 0x01, 0x2A };
compare(arr1, arr2);
}

Why have you got nested loops?

I can’t use the memcmp on the mcu that I’m using.

huh?

bool compare(unsigned char a[], unsigned char b[])
{
  for (int i = 0; i < 4; i++)
  {
    if (a[i] != b[i])
   {
      return false;   
    }   
  }
  return true;
}

Or even:

bool compare (byte a[], byte b[])
{
  byte sum = 0 ;
  for (int i = 0; i < 4; i++)
    sum |= a[i] ^ b[i] ;
  return sum == 0 ;
}

Although that takes the same time to run however different the arrays are
(sometimes an advantage, ie in cryptography)

I can't use the memcmp on the mcu that I'm using.

You can use memcmp() on ANY Arduino. If you aren't using an Arduino WTF are you doing here?