While debugging my implementation of YMODEM on an embedded system, I noticed that some code comparing a uint8_t and the inverse of a uint8_t is not behaving as I expected, but I don't really understand why. To test that this is really the case in C and not just wierd behaviour of my embedded system, I wrote the following
#include <stdio.h>
#include <stdint.h>
int main(int argc, char ** argv)
{
uint8_t num1 = 0;
uint8_t num2 = 255;
printf("%d\n", num1 == ~num2);
return 0;
}
If I have a uint8_t with the value 0x00, then the inverse should be 0xFF, right? So this program should print 1. However, it prints 0, indicating that 0x00 != ~0xFF.
Why does this happen?
num2is promoted to anint, with the value0x000000ff(assuming 32-bitint). When you then complement it, you get0xffffff00which is indeed not equal to0.