Search code examples
c++gcccastingunsigned-char

Sign conversion when ANDing and comparing


I have the following code:

const uint8_t HEADER_SIZE = 0x08;
std::vector<uint8_t> a, b;
uint8_t x;

/* populate 'a', 'b'. Set 'x' */

for ( uint8_t i = 0; i < HEADER_SIZE; ++i )
{
    // The if statement (specifically the AND): Conversion to 'unsigned int' from 'int' may change the sign of the result [-Wsign-conversion]
    if ( x != ( a[i + HEADER_SIZE] & b[i] ) )
    {
         /* ... */
         break;
    }
}

I tried casting almost everything, and I cannot seem to figure out why a simple AND is causing this warning. Both variables are unsigned. Any ideas?


Solution

  • Your uint8_t's get promoted to int before being &ed together. Then that int is being compared to x, which is still uint8_t. Same thing happens with i + HEADER_SIZE. Casting results back to uint8_t should get rid of the warning.

    x != uint8_t(a[uint8_t(i + HEADER_SIZE)] & b[i])