JavaForStarters
JavaForStarters

Reputation: 71

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.

Upvotes: 2

Views: 96

Answers (4)

Giorgi Moniava
Giorgi Moniava

Reputation: 28654

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.

Upvotes: 2

R Sahu
R Sahu

Reputation: 206577

~(array[1]) evalutes to ~(0x0A). On a platform where an int is a 32-bit number, due to integer promotion, that is equivalent to ~(0x0000000A), which is the same as 0xFFFFFFF5.

Hence, 0xF5 == ~(array[1]) translates to 0xF5 == 0xFFFFFFF5, which obviously evaluates to false.

In order to make your comparison work, you can use another bitwise operator.

if( 0xF5 == (~(array[1]) & 0xFF) )

This makes sure that everything but the last bit of the promoted integer on the RHS of the == operator is zeroed out.

Upvotes: 2

Ian Abbott
Ian Abbott

Reputation: 17403

Use:

if (0xF5 == (uint8_t)~(array[1])){

or:

if (0xF5 == (~(array[1]) & 0xFF)){

Upvotes: 2

Tom Karzes
Tom Karzes

Reputation: 24052

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]) {
    ...
}

Upvotes: 3

Related Questions