tags:

views:

2289

answers:

3

Hi, in C++ I have two chars holding hex values e.g.:

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

How would i compare if the two values held in the char are the same?? I tried

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

but no, any help, thanks!

A: 

Ah, I found the solution:

if (t & q)
BobS
dwj
In any case, this isn't what he asked. If t and q are initialized as presented, then t==q certainly gives true - atleast with my compiler.
Martin v. Löwis
That works for all values Except: t = q = 0.
Martin York
Martin the problem with it is mostly that it works for too many values. Example t= 3 and q = 1.
Brian R. Bondy
BobS, while I think the downvoting has been a bit excessive here, I think you should have just edited your question and added this info to the end of it.
MattSmith
+1  A: 

Works fine for me.

Shadow2531
+9  A: 

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.

Brian R. Bondy