derrdji
derrdji

Reputation: 13321

How to test a byte against a hex value?

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.

Upvotes: 3

Views: 4853

Answers (2)

Doug T.
Doug T.

Reputation: 65599

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.

Upvotes: 9

Clifford
Clifford

Reputation: 93476

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

if( aChar == '\xee' )

Upvotes: 6

Related Questions