C语言 C if 语句 OR AND 上的逻辑运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16180791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:09:41  来源:igfitidea点击:

C Logical operators on if statement OR AND

coperators

提问by zikdaljin

Something is wrong with this logic it detects everything and prints bad pkt detected.

这个逻辑有问题,它检测一切并打印bad pkt detected

if((buff[0] != 0x0a || buff[0] != 0x0e) && (len == 210))
{
    printf("badpkt detected from %s\n", xpi);
} else {
    if(mysend(ssl_sd ? ssl_sd[i] : NULL, sd[i], buff, len) <= 0) MULTI_SKIP_QUIT
}

The logic is DENY all packets that are 210 in length. Except if the 1st byte is 0x0A or 0x0E.

逻辑是拒绝所有长度为 210 的数据包。除非第一个字节是 0x0A 或 0x0E。

This code is working though:

这段代码虽然有效:

if((buff[0] != 0x0a) && (len == 210))
{
    printf("badpkt detected from %s\n", xpi);
} else {
    if(mysend(ssl_sd ? ssl_sd[i] : NULL, sd[i], buff, len) <= 0) MULTI_SKIP_QUIT
}

But I need both 0x0aand 0x0eto be the only 210 length packet allowed.

但是我需要两者0x0a并且0x0e是唯一允许的 210 长度数据包。

edit

编辑

What was I thinking, maybe its the lack of sleep.

我在想什么,也许是睡眠不足。

回答by Pol0nium

If you want both 0x0aand 0x0eallowed, you need to use this condition :

如果您既想要0x0a0x0e允许,则需要使用此条件:

if((buff[0] == 0x0a || buff[0] == 0x0e) && (len == 210))

回答by Jacob Seleznev

This (buff[0] != 0x0a || buff[0] != 0x0e)is always true.

(buff[0] != 0x0a || buff[0] != 0x0e)总是正确的

It should be if(buff[0] != 0x0a && buff[0] != 0x0e && (len == 210))

它应该是 if(buff[0] != 0x0a && buff[0] != 0x0e && (len == 210))

回答by nos

You need this logic:

你需要这个逻辑:

if(buff[0] != 0x0a && buff[0] != 0x0e && len == 210)

With this condition:

在这个条件下:

 if((buff[0] != 0x0a || buff[0] != 0x0e) && (len == 210))

imagine buff[0]is 0x0e. Then buff[0] != 0x0awill be true, which makes the whole sub expression (buff[0] != 0x0a || buff[0] != 0x0e)be true.

想象buff[0]IS 0x0e。然后buff[0] != 0x0a将为真,这使得整个子表达式(buff[0] != 0x0a || buff[0] != 0x0e)为真。

You could also invert the condition:

您还可以反转条件:

if((buff[0] == 0x0a || buff[0] == 0x0e) //always allow these
     || (len != 210)) //and allow anything thats not of length 210
{
    if(mysend(ssl_sd ? ssl_sd[i] : NULL, sd[i], buff, len) <= 0) 
         MULTI_SKIP_QUIT

} else {
     printf("badpkt detected from %s\n", xpi);
}