Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare hex values using C?

Tags:

c

hex

I am working with hex values. Until now I know how to print hex values and also precision thing. Now I want to compare 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?

like image 230
mainajaved Avatar asked Oct 14 '11 12:10

mainajaved


2 Answers

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 '?'.

like image 58
Paul R Avatar answered Sep 19 '22 14:09

Paul R


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)
like image 24
Shahbaz Avatar answered Sep 19 '22 14:09

Shahbaz