In this little program:
#include <unistd.h>
#include <stdint.h>
#include <stdio.h>
int main() {
uint8_t a = 0;
uint8_t b = 255;
if (a == (b + 1)) {
printf("Equal\n");
} else {
printf("Not equal\n");
}
if (a == ((b + 1) & 0xFF)) {
printf("Equal\n");
} else {
printf("Not equal\n");
}
}
I get:
Not Equal
Equal
Why doesn’t the comparison work unless I forcibly take the last 8 bits? I’m guessing I’m missing some nuance of unsigned arithmetic here…
I’m using gcc 4.4.5 if that makes a difference.
Because of integer promotions, both operands of the
==and+operator are promoted toint.The expression:
is then equivalent to:
which is false.
The expression:
a == (uint8_t) (b + 1)would give you the result you expect (true). Another solution is to use& 0xFFlike in your secondifstatement,