1

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!

2
  • Wait, something's wrong here. That should, and does execute if branch of the conditional. We need more context. Your "a & b" answer is not correct - that will be "true" for any overlapping bits in the representation of a and b Nov 2, 2008 at 20:19
  • That should work. Why do you think it does not? Nov 2, 2008 at 20:45

2 Answers 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.

-8

Ah, I found the solution:

if (t & q)
4
  • That should be if ( t && q ) Your statement, (t & q), does a bit-wise comparison. Granted, this may be what you want.
    – dwj
    Nov 2, 2008 at 20:15
  • 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. Nov 2, 2008 at 20:21
  • Martin the problem with it is mostly that it works for too many values. Example t= 3 and q = 1. Nov 2, 2008 at 20:50
  • 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. Nov 3, 2008 at 5:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.