sailfish009
sailfish009

Reputation: 2929

fastest way to compare array with incoming byte* buffer

Is there any fastest way to compare 24 element byte array with incoming byte* buffer?

byte compare_array[24]=
{0x00,0x00,0x00,0x01,0x26,0x05,
 0xF8,0x00,0x11,0x22,0x33,0x44,
 0x55,0x66,0x77,0x88,0x99,0xAA,
 0xBB,0xCC,0xDD,0xEE,0xFF,0xFF};

below code doesn't feel alright.

if( (buffer[0] == 0x00) && (buffer[1] == 0x00) && ...)
{
  //...
}

Upvotes: 1

Views: 185

Answers (2)

perreal
perreal

Reputation: 97938

this may be faster, if the arrays are aligned:

bool compare(uint8_t* buffer) {
  uint64_t *c64 = (uint64_t*)compare_array;
  uint64_t *b64 = (uint64_t*)buffer;
  return c64[0] == b64[0] && c64[1] == b64[1] && c64[2] == b64[2];
}

Upvotes: 1

Monza
Monza

Reputation: 755

I agree with your observation that the code doesn't feel right. What you need is a loop. A for loop or a do while loop. In both cases you can break out early as soon as you find a differing byte. The early-pruning of checking array lengths as Kltis mentioned is the easiest way to save runtime early on.

If you really need to go deeper, have a look at the memcmp() function.

Good luck!

Upvotes: 0

Related Questions