C job interview - casting and comparing

后端 未结 10 712
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  礼貌的吻别
    2021-02-01 13:04

    You have a MAC structure (which contains an array of 6 bytes),

    typedef struct {
        char data[6];
    } MAC;
    

    Which agrees with this article about typedef for fixed length byte array.

    The naive approach would be to assume the MAC address is word aligned (which is probably what the interviewer wanted), albeit not guaranteed.

    typedef unsigned long u32;
    typedef   signed long s32;
    typedef unsigned short u16;
    typedef   signed short s16;
    
    int
    MACcmp(MAC* mac1, MAC* mac2)
    {
        if(!mac1 || !mac2) return(-1); //check for NULL args
        u32 m1 = *(u32*)mac1->data;
        U32 m2 = *(u32*)mac2->data;
        if( m1 != m2 ) return (s32)m1 - (s32)m2;
        u16 m3 = *(u16*)(mac1->data+4);
        u16 m2 = *(u16*)(mac2->data+4);
        return (s16)m3 - (s16)m4;
    }
    

    Slightly safer would be to interpret the char[6] as a short[3] (MAC more likely to be aligned on even byte boundaries than odd),

    typedef unsigned short u16;
    typedef   signed short s16;
    
    int
    MACcmp(MAC* mac1, MAC* mac2)
    {
        if(!mac1 || !mac2) return(-1); //check for NULL args
        u16* p1 = (u16*)mac1->data;
        u16* p2 = (u16*)mac2->data;
        for( n=0; n<3; ++n ) {
            if( *p1 != *p2 ) return (s16)*p1 - (s16)*p2;
        }
        return(0);
    }
    

    Assume nothing, and copy to word aligned storage, but the only reason for typecasting here is to satisfy the interviewer,

    typedef unsigned short u16;
    typedef   signed short s16;
    
    int
    MACcmp(MAC* mac1, MAC* mac2)
    {
        if(!mac1 || !mac2) return(-1); //check for NULL args
        u16 m1[3]; u16 p2[3];
        memcpy(m1,mac1->data,6);
        memcpy(m2,mac2->data,6);
        for( n=0; n<3; ++n ) {
            if( m1[n] != m2[n] ) return (s16)m1[n] - (s16)m2[n];
        }
        return(0);
    }
    

    Save yourself lots of work,

    int
    MACcmp(MAC* mac1, MAC* mac2)
    {
        if(!mac1 || !mac2) return(-1);
        return memcmp(mac1->data,mac2->data,6);
    }
    

提交回复
热议问题