首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么这种字符比较会导致错误?

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

Stack Overflow用户
提问于 2021-11-13 04:08:38
回答 1查看 49关注 0票数 0

在这个函数中,我尝试检查char数组是否包含广播MAC地址。为此,我将每个数组元素与0xFF进行比较。

代码语言:javascript
运行
复制
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;
}

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

代码语言:javascript
运行
复制
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

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

代码语言:javascript
运行
复制
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行。

导致这些错误的是这种比较有什么问题吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-13 10:31:30

常量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的类型改为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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69951375

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档