tags:

views:

330

answers:

4

Hi, if I have a range of say 000080-0007FF and I want to see if a char containing hex is within that range, how can I do this? Thanks a lot.

Example

char t = 0xd790;

if (t is within range of 000080-0007FF) // true

Thanks

+7  A: 
wchar_t t = 0xd790;

if (t >= 0x80 && t <= 0x7ff) ...

In C++, characters are interchangeable with integers and you can compare their values directly.

Note that I used wchar_t, because the char data type can only hold values up to 0xFF.

Greg Hewgill
+1  A: 

@Greg, I tried it and I get warning: comparison is always false due to limited range of data type

Ok just read your fix

BobS
It sounds like your compiler is set to interpret 'char' as a signed data type (which ranges from -128 to 127). Use wchar_t as I edited my answer.
Greg Hewgill
Is there another way other than wchar_t?
BobS
yes, use a short which is 16 bits. Actually you really should be using unsigned values. So unsigned short.
Brian R. Bondy
+3  A: 
unsigned short t = 0xd790;

if (t >= 0x80 && t <= 0x7ff) ...

Since a char has a max value of 0xFF you cannot use it to compare anything with more hex digits than 2.

Brian R. Bondy
A: 

Since hex on a computer is nothing more than a way to print a number (like decimal), you can also do your comparison with plain old base 10 integers.

if( (t >= 128) && (t <= 2047) ) { }

More readable.

dicroce
No. I would disagree. The Hex values are more readable. You can see the bit patterns from the hex values.
Martin York
Readability is entirely dependent on context. If the bit patterns are relevant to the problem at hand hex is more readable (presumably this is the OP's case). If the numbers represent something like normal counts of items, decimal is more readable.
Steve Fallows