How to compare hexadecimal values ​​with C?

I work with hexadecimal values. So far, I know how to print hexadecimal values, as well as precision. Now I want to compare hexadecimal values. For example, I am reading data from a file into a char buffer. Now I want to compare the hexadecimal value of the data in the buffer. Is there anything similar?

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

How can i do this?

+4
source share
5 answers

You are almost there:

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

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

+11
source

Yes, you can:

  if (buffer[i] > 0x3F) 

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

+4
source

The numbers on the computer are all 0 and 1. If you look at them in base 10 or base 16 (hexadecimal) or as a character (for example, "a"), this will not change the number.

So, to compare with hex, you don't have 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) 
+3
source

When comparing char with hex, you have to be careful:

Using the == operator to compare char with 0x80 always results in an error?

I would recommend this syntax introduced in C99 to be sure

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

It tells the compiler that 0x3f is a char, not an int (security type), otherwise you will probably see a problem with this comparison.

In fact, the clang compiler will warn you about this:

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

+1
source

Hexadecimal values ​​are not new data types, but simply other digital methods, such as

int a = 10;

in hexadecimal

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

output

 a in hex value A 

in if loop

 if(a == 0xa) do something 

in decimal form

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

output

 a in hex value 10 

in if loop

 if(a == 10) do something 
0
source

All Articles