C job interview - casting and comparing

后端 未结 10 717
没有蜡笔的小新
没有蜡笔的小新 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:55

    Cowboy time:

    typedef struct macA {
       char data[6];
    } MAC;
    
    typedef struct sometimes_works {
       long some;
       short more;
    } cast_it
    
    typedef union cowboy
    {
        MAC real;
        cast_it hack;
    } cowboy_cast;
    
    int isEqual(MAC* addr1, MAC* addr2)
    {
         assert(sizeof(MAC) == sizeof(cowboy_cast));  // Can't be bigger
         assert(sizeof(MAC) == sizeof(cast_it));      // Can't be smaller
    
         if ( ( ((cowboy_cast *)addr1)->hack.some == ((cowboy_cast *)addr2)->hack.some )
           && ( ((cowboy_cast *)addr1)->hack.more == ((cowboy_cast *)addr2)->hack.more ) )
                 return (0 == 0);
    
         return (0 == 42);
    }
    

提交回复
热议问题