C job interview - casting and comparing

后端 未结 10 737
没有蜡笔的小新
没有蜡笔的小新 2021-02-01 12:29

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

10条回答
  •  旧时难觅i
    2021-02-01 12:53

    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.

提交回复
热议问题