I was confronted with a tricky (IMO) question. I needed to compare two MAC addresses, in the most efficient manner.
The only thought that crossed my mind in that moment
Non-portable casting solution.
In a platform I use (PIC24 based), there is a type int48
, so making a safe assumption char
is 8 bits and the usual alignment requirements:
int isEqual(MAC* addr1, MAC* addr2) {
return *((int48_t*) &addr1->data) == *((int48_t*) &addr2->data);
}
Of course, this is not usable on many platforms, but then so are a number of solutions that are not portable either, depending on assumed int
size, no padding
, etc.
The highest portable solution (and reasonably fast given a good compiler) is the memcmp()
offered by @H2CO3.
Going to a higher design level and using a wide enough integer type like uint64_t
instead of struct macA
, as suggested by Kerrek SB, is very appealing.