Question

    unsigned char Mid;

if( (data[2]) == 0x9A){
    Mid = data[5];

    if( (Mid == 1) || (Mid == 2) || (Mid == 3) )
        return(Mid);

The code above gives:

warning: comparison is always false due to limited range of data type

error as I expected.

It's ok if I type

if( (unsigned char)data[2] == 0x9A){

or

if( (data[2]&0xFF) == 0x9A){

I understand the first one, but what happens in the second one?

What is the effect of masking with 0xFF?

Was it helpful?

Solution

  • When casting the value to unsigned char, you are doing an explicit type conversion.

  • When you mask the value with 0xFF, an implicit type conversion takes place.

You have the signed char data[2] and 0xFF as operands to the bitwise AND operator. Because one of the operands (0xFF) cannot fit inside a signed char, both operands are implicitly converted into an unsigned type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top