I've tried to invert an array element today and it didn't work. Is there a reason that e.g.
uint8_t array[2] = {0xFF,0x0A};
...
if( 0xF5 == ~(array[1]){
// never got here
}
Doesn't work? Compiler didn't show any errors.
C promotes integer types to int (or larger) when performing integer arithmetic. To get the value you desire, you can cast the result of the bitwise complement back down to uint8_t before comparing, as follows:
if (0xF5 == (uint8_t) ~array[1]) {
...
}
if(0xF5 == ~(array[1]))
This happens because array[1] is promoted to int before inversion is applied to it. Hence when you apply inversion on promoted value of array[1] you get: 0xFFFFFFF5, which is not equal to 0x000000F5
As noted you can cast the expression on the right hand side of the equality operator to uint8_t if you want to do comparison.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With