为什么这个字符比较会出错?

Why does this char comparison cause errors?

在这个函数中,我试图检查一个字符数组是否包含广播 MAC 地址。我将每个数组元素与 0xFF 进行比较以执行此操作。

static inline bool recibir_trama_l2_en_interface(interface_t *interface, cab_ethernet_t *cab_ethernet) {
    char *mac = MAC_IF(interface);
    if(IF_EN_MODO_L3(interface)) {
        char *mac_destino = cab_ethernet->mac_destino.dir_mac;
        mostrar_dir_mac(&interface->prop_intf->dir_mac);
        mostrar_dir_mac(&cab_ethernet->mac_destino);
        bool bandera_prueba = true;
        bandera_prueba = mac_destino[0] == 0xFF;            

        if(mac_destino[0] == 0xFF && mac_destino[1] == 0xFF && mac_destino[2] == 0xFF && mac_destino[3] == 0xFF && mac_destino[4] == 0xFF && mac_destino[5] == 0xFF) {
            printf("Esto está pasando.\n");
        }
        printf("AABBNINKD.\n");
        if(mac_destino[0] == 0xFF) {
            printf("Esto sí pasa.\n");
        }    
    }
    return false;
}

这些是我正在使用的结构。

typedef struct cab_ethernet_ {
    dir_mac_t mac_destino;
    dir_mac_t mac_origen;
    short tipo;
    char payload[TAM_MAX_PAYLOAD];
    unsigned int FCS;
} cab_ethernet_t;

typedef struct dir_mac_ {
    char dir_mac[TAM_DIR_MAC];
} dir_mac_t;

调试器告诉我 mac_destino[0] 的内容是 0xFF。但是也可以看到,对比之后,bandera_prueba设置为false

发生的另一件事是程序显然正在跳过这些指令。

if(mac_destino[0] == 0xFF && mac_destino[1] == 0xFF && mac_destino[2] == 0xFF && mac_destino[3] == 0xFF && mac_destino[4] == 0xFF && mac_destino[5] == 0xFF) {
    printf("Esto está pasando.\n");
}

if(mac_destino[0] == 0xFF) {
    printf("Esto sí pasa.\n");
}

我的意思是,调试器从第 78 行跳到第 83 行,再到第 89 行。 这种比较有什么问题导致这些错误吗?

常量 0xFF 的值为 255。在您的 C 实现中,char 是有符号的并且只能具有值 −128 到 +127。 mac_destino[0] 是一个 char。因此 mac_destino[0] == 0xFF 永远不可能为真。在调试器中逐步执行代码似乎会跳过行,因为编译器已优化程序以省略不可能的部分。

要解决此问题,请将使用的类型更改为 unsigned char

最好将struct dir_mac_dir_mac的元素类型改为unsigned charmac_destino的元素类型改为unsigned char *。如果您不能这样做,请将 mac_destino 的定义从 char *mac_destino = cab_ethernet->mac_destino.dir_mac; 更改为 unsigned char *mac_destino = (unsigned char *) cab_ethernet->mac_destino.dir_mac;

如果您不能这样做,您可以在每个比较中插入一个转换,如将 mac_destino[0] == 0xFF 更改为 (unsigned char) mac_destino[0] == 0xFF