繁体   English   中英

为什么这个字符比较会导致错误?

[英]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 char ,将mac_destino的类型mac_destinounsigned char * 如果您不能这样做, mac_destinochar *mac_destino = cab_ethernet->mac_destino.dir_mac;更改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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM