簡體   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