Ç面试 - 铸造和比较 [英] C job interview - casting and comparing

查看:116
本文介绍了Ç面试 - 铸造和比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临着一个棘手的(IMO)的问题。我需要比较两个 MAC地址,以最有效的方式。

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 was the trivial solution - a for loop, and comparing locations, and so I did, but the interviewer was aiming to casting.

该MAC定义:

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

和作用是(一个我被要求执行):

And the function is (the one I was asked to implement):

int isEqual(MAC* addr1, MAC* addr2)
{
    int i;

    for(i = 0; i<6; i++)
    {
        if(addr1->data[i] != addr2->data[i]) 
            return 0;
    }
    return 1;
}

但是如前所述,他瞄准铸造。

But as mentioned, he was aiming for casting.

含义,以某种方式给予投为int的MAC地址,比较这两个地址,然后返回。

Meaning, to somehow cast the MAC address given to an int, compare both of the addresses, and return.

但铸造时, INT int_addr1 =(INT)ADDR1; ,只有四个字节将被浇铸成型,对不对?我应该检查其余的?含义位置4和5?

But when casting, int int_addr1 = (int)addr1;, only four bytes will be casted, right? Should I check the remaining ones? Meaning locations 4 and 5?

两者字符 INT 的整数类型,以便浇铸是合法的,但会发生什么
在所描述的情况呢?

Both char and int are integer types so casting is legal, but what happens in the described situation?

推荐答案

如果他是这个方法(这基本上是一个大脑屁真的不满,因为你没有比较兆或千兆字节的数据,所以一不得真正担心在这种情况下,效率和速度),就告诉他,你相信标准库的质量和速度:

If he is really dissatisfied with this approach (which is essentially a brain fart, since you aren't comparing megabytes or gigabytes of data, so one shan't really be worrying about "efficiency" and "speed" in this case), just tell him that you trust the quality and speed of the standard library:

int isEqual(MAC* addr1, MAC* addr2)
{
    return memcmp(&addr1->data, &addr2->data, sizeof(addr1->data)) == 0;
}

这篇关于Ç面试 - 铸造和比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆