比较 8 位无符号整数与 HEX 失败

Comparing 8 - bit Unsigned Integer to HEX Failing

我有一个 C++ 向量,其中包含来自 TCP 数据段的 uint8_t 个值。我专门寻找两个值中的一个,它应该位于向量的第一个索引处。

我有下面的if语句来表达我的逻辑。

if ( ui8BufferIn.at(0) != 0xE4 || ui8BufferIn.at(0) != 0xE2){
    printf("\nWe have a problem, no parsing will be done, Package Type = %u\n", ui8BufferIn.at(0));
    proceed = false;
}

上面的 if 语句在不应该执行的时候执行。我得到以下打印输出:

We have a problem, no parsing will be done, Package Type = 226

因此您不必进行数学运算,226 作为一个整数在十六进制中是 0xE2

我已经有一段时间了,所以它很可能很简单,但任何帮助都会很棒!

我想你可能希望你的逻辑是:

if ( ui8BufferIn.at(0) != 0xE4 && ui8BufferIn.at(0) != 0xE2){

你现在说的是 "If either case of: (it's not 0xE4) or case of: (it's not 0xE2), we have a problem" - 如果我理解正确的话,这不是你想说的。使用您的语句,您可能会得到 0xE2,但是因为您没有得到 0xE4 (ui8BufferIn.at(0) != 0xE4),所以您的语句会执行。

您的代码中存在一个小的逻辑错误。在这种情况下,您的错误将始终出现。假设 uint8_t 值为 0xE2。您将获得以下条件:

if(0xE2 != 0xE4 || 0xE2 != 0xE2)
    //Error

计算结果为:

if(true || false) //Actually the second operand will not be evaluated
    //Error

这将执行您的错误条件。实际上对于任何给定的输入,你的错误函数都会执行。除非您的 uint8_t 值设法与 0xE20xE4 进行比较,但据我所知,目前不存在这样的值。

最简单的解决方案是将您的 'or' 更改为 'and',给出以下代码:

if(ui8BufferIn.at(0) != 0xE4 && ui8BufferIn.at(0) != 0xE2)
    //Error

你的逻辑是这样的:

If (value is not (value a)) OR (value is not (value b)) then...

让我们看看可能性:

Value = a: then value is not b: result is true
Value = b: then value is not a: result is true
Value = other: the value is not a: result is true

所以 if 语句的计算结果总是为真