开发者

How to compare hex values using C?

开发者 https://www.devze.com 2023-04-12 20:06 出处:网络
I am working with hex values. Until now I know how to print hex values and also precision thing. Now I want to compa开发者_开发问答re the hex values. For example I am reading data from a file into a c

I am working with hex values. Until now I know how to print hex values and also precision thing. Now I want to compa开发者_开发问答re the hex values. For example I am reading data from a file into a char buffer. Now I want to compare the hex value of data in the buffer. Is there anything like this?

if  hex(buffer[i]) > 0X3F  
then
//do somthing

How can I do this?


You're nearly there:

if (buffer[i] > 0x3f)
{
    // do something
}

Note that there is no need to "convert" anything to hex - you can just compare character or integer values directly, since a hex constant such as 0x3f is just another way of representing an integer value. 0x3f == 63 (decimal) == ASCII '?'.


Numbers in the computer are all 0s and 1s. Looking at them in base 10, or base 16 (hex) , or as a character (such as 'a') doesn't change the number.

So, to compare with hex, you don't need to do anything.

For example, if you have

int a = 71;

Then the following two statements are equivalent:

if (a == 71)

and

if (a == 0x47)


Yes you can:

 if  (buffer[i] > 0x3F)

(note the lowercase x). Edit it turns out 0X3F should work just as well, but I am tempted to say it is not what C programmers usually write).


When comparing char to hex you must be careful:

Using the == operator to compare a char to 0x80 always results in false?

I would recommend this syntax introduced in C99 to be sure

if (buffer[i] > '\x3f')
{
    // do something
}

It tells the compiler that the 0x3f is a char rather than an int (type-safety), otherwise it is likely you will see issue with this comparison.

In fact clang compiler will warn you about this:

comparison of constant 128 with expression of type 'char' is always false [-Werror,-Wtautological-constant-out-of-range-compare]


Hex values are nothing new data types its just another numberical methods like

int a = 10;

in Hex printing

printf("a in hex value %x ",a);

output is

a in hex value A

in if loop

if(a == 0xa)
    do something

in decimal

printf("a in decimal value %d ",a);

output is

a in hex value 10

in if loop

if(a == 10)
    do something
0

精彩评论

暂无评论...
验证码 换一张
取 消