简体   繁体   English

如何使用C比较十六进制值?

[英]How to compare hex values using C?

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. 例如,我正在将文件中的数据读入char缓冲区。 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)只是表示整数值的另一种方式。 0x3f == 63 (decimal) == ASCII '?'. 0x3f == 63(十进制)== ASCII'?'。

Numbers in the computer are all 0s and 1s. 计算机中的数字都是0和1。 Looking at them in base 10, or base 16 (hex) , or as a character (such as 'a') doesn't change the number. 在基数10或基数16(十六进制)或作为字符(例如“a”)查看它们不会更改数字。

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). (注意小写的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). 编辑它结果是0X3F应该工作,但我很想说这不是C程序员通常写的东西)。

When comparing char to hex you must be careful: 将char与hex进行比较时,必须小心:

Using the == operator to compare a char to 0x80 always results in false? 使用==运算符将char与0x80进行比较总是会导致错误?

I would recommend this syntax introduced in C99 to be sure 我建议在C99中引入这种语法

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. 它告诉编译器0x3f是char而不是int(类型安全),否则你很可能会看到这个比较的问题。

In fact clang compiler will warn you about this: 事实上,clang编译器会警告你:

comparison of constant 128 with expression of type 'char' is always false [-Werror,-Wtautological-constant-out-of-range-compare] 常量128与'char'类型表达式的比较始终为false [-Werror,-Wautological-constant-out-of-range-compare]

Hex values are nothing new data types its just another numberical methods like 十六进制值不是新的数据类型,它只是另一种数字方法

int a = 10; int a = 10;

in Hex printing 在六角印刷中

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

output is 输出是

a in hex value A

in if loop 在if循环中

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循环中

if(a == 10)
    do something

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM