tags:

views:

206

answers:

2

I want to test if the byte I read from a data file is 0xEE, what should I do? I tried if (aChar == 0xEE) but doesn't seems working. thanks for any help

+8  A: 

When reading a signed char, the value will never be 0xEE. IE:

#include <stdio.h>

int main()
{
    char c = 0xEE;   // assumes your implementation defines char as signed char
    // c is now -18
    if (c == 0xEE)
    {
        printf("Char c is 0xEE");
    }
    else
    {
        printf("Char c is NOT 0xEE");
    }

}

The output will be

Char c is NOT 0xEE

When the signed character is read, the value will range from -0x7F to 0x80. An unsigned char is interpreted from 0x00 up to 0xFF, and is typically what you want for "raw" bytes.

Change:

char aChar;

to

unsigned char aChar;

and it should work.

Doug T.
It should be noted that a plain old char can be either signed or unsigned; it's up to the implementation.
James McNellis
@Martin That's complete semantics. I know you can assign it 0xFF, but the test if a signed char is 0xFF will always fail.
Doug T.
Just to reiterate James McNellis, it's implementation-dependent whether your example works or not.
rlbond
@Doug T: Why will it always fail? If 0xEE isn't representable in a char, then it gets converted to the equivalent negative value anyway, and then it might compare equal to the char.
jalf
@jalf: If `char` is a signed type, then `char c = 0xEE;` results in `c` being a negative value (-18) and testing `c == 0xEE` will always fail. Since the hexadecimal integer literal `0xEE` is of type `int`, the `char` will be promoted to `int` for the comparison. `-18 != 238`.
James McNellis
+6  A: 

Using a character constant will avoid any implementation defined signed/unsigned character type issues:

if( aChar == '\xee' )
Clifford