1

在 C++ 中,我有两个保存十六进制值的字符,例如:

char t = 0x4;
char q = 0x4;

如果 char 中保存的两个值相同,我将如何比较?我试过了

if (t == q) // should give me true

但不,任何帮助,谢谢!

4

2 回答 2

11

A char is just an 8-bit integer. It doesn't matter if you initialized it with hex or decimal literal, in either case the value of the char will be the same afterwards.

So:

char t = 0x4;
char q = 0x4;
if(t == q)
{
 //They are the same
}

It is equivalent to:

char t = 4;
char q = 4;
if(t == q)
{
 //They are the same
}

You mentioned that the above is not true, but you must have an error in your code or t and q must not be the same.

What you suggested...

if (t == q) // should give me true but no, any help, thanks!

is not correct. Why?

t & q does a bitwise compare, returning a value where both aligned bits are 1.

The term "if(t&q)" would return true as long as any of the bits of t and q are in common.

so if t = 3 which is in binary 00000011 and q = 1 which is in binary 00000001 then (t&q) would return true even know they are not equal.

于 2008-11-02T20:21:13.100 回答
-8

啊,我找到了解决方案:

if (t & q)
于 2008-11-02T20:12:46.780 回答