Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverting array elements (bitwise) doesn't work

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.

like image 540
JavaForStarters Avatar asked Aug 06 '26 07:08

JavaForStarters


2 Answers

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]) {
    ...
}
like image 194
Tom Karzes Avatar answered Aug 07 '26 21:08

Tom Karzes


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.

like image 27
Giorgi Moniava Avatar answered Aug 07 '26 22:08

Giorgi Moniava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!