How do I compare a Signed Char with a literal constant?

The API provides a function signed char getDirection();

that returns 1 for "forward", 0 for "stationary", -1 for "backward".

And of course, as explained in these questions , a simple comparison:

    if(getDirection() == -1) { ... }

      

fails. Ok I understand why it is failing. But I just can't seem to find how to make it work! I tried pouring left side on (int)

, right side up (signed char)

, still nada ...

change:

 signed char a = getDirection();
 printf("%d\n",(int) a);
 printf("%d\n",(int) getDirection());

      

Results:

 -1
 255

      

edit2: per request:

const signed char getDirection(uchar d)
{
    if(d >= config.directional_inputs.channelCount) return -2;

    return shm->input_state.directional_inputs[d].direction;
}

      

+3


source to share


3 answers


If you are sure you are getDirection()

indeed returning a signed char, it should work, since the signed char of 0xff

should be properly promoted to -1 integer.

If you are not sure, you can try writing



int dir = getDirection();
// optionnally for extensive tests : fprintf(stderr, "getDirection : %d\n", dir);
if ((dir == -1) || (dir == 255)) { ... }

      

255 will catch any conversion problem like getDirection()

returning a signed char ... what your last change suggests ...

0


source


It seems that the part GetDirection

is being executed return shm->input_state.directional_inputs[d].direction;

. What is the type of this item direction

? I'm not sure about the promotions here, but if it is unsigned char

, it could just be copied into the return register ax

and returned. That is, sign expansion is not performed, while ax is 0x000000ff

. ff

is assigned signed char a

which is correct, and when a

used in a call printf

it gets the correct sign. Thus, sign expansion has to be done in the return statement GetDirection

, where it appears to fail.



Try changing it to return (signed char)shm->input_state.directional_inputs[d].direction;

0


source


It is very strange.

First, using different compilers can make a difference. They can have different rules, as it is assumed that a signed char is expected to return. Let's say the compiler to compile a function assumes that signed char is returned as 8 bits in a 32-bit register and the remaining bits are zero or undefined -1 are returned as 00000000 00000000 00000000 11111111. The compiler for the call assumes that signed char is returned as 8 bits in 32 -bit register, the sign is expanded, and therefore all 32 bits can be considered to contain the correct value. So the compiler thinks the result is 255.

Secondly, I saw problems when prototypes and functions did not match. If there is a function prototype somewhere that says "char" instead of a signed char, that explains everything. Since the problem is weird, I would ask the compiler to output the preprocessor and check if something weird is happening.

0


source







All Articles