[英]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.