[英]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");
}
常量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_destino
為unsigned char *
。 如果您不能這樣做, mac_destino
從char *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.