tags:

views:

153

answers:

5

I'm trying to make a macro in C that can tell if a char is a hex number ( 0-9 a-z A-Z)

#define _hex(x) (((x) >= "0" && (x) <= "9" )||( (x) >= "a" && (x) <= "z") || ((x) >= "A" && (x) <= "Z") ? "true" : "false")

This what I've come up with but it won't work with a loop like this

char a;
     for(a = "a" ; a < "z";a++){
        printf("%s  => %s",a, _hex(a));
     }

it gives an error

test.c:8: warning: assignment makes integer from pointer without a cast
test.c:8: warning: comparison between pointer and integer
test.c:9: warning: comparison between pointer and integer
test.c:9: warning: comparison between pointer and integer
test.c:9: warning: comparison between pointer and integer
test.c:9: warning: comparison between pointer and integer
test.c:9: warning: comparison between pointer and integer
test.c:9: warning: comparison between pointer and integer
+9  A: 

"a" is a pointer to a string "a". You want to compare the char to 'a' instead.

#define _hex(x) (((x) >= '0' && (x) <= '9' )||( (x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z') ? "true" : "false")

But you can also use isalnum(x) instead - it returns true if the character is a digit or a character.

Or isxdigit(x) if it was really supposed to be a hex check.

viraptor
+1 for isalnum suggestion.
Mark Byers
my intention whas a-f ;p for HEX numbers :) but hadnt implemented in this example
Spidfire
@viraptor: please, correct your answer replacing `zZ` by `fF`.
jweyrich
@jweyrich: It is the question that needs correcting first!
Clifford
Added isxdigit() - I think everything's clear that way.
viraptor
+2  A: 

Use isxdigit() then.

Nikel
A: 

You also need to change your "for" loop to loop over the range 'a' to 'z' instead of over the "a" to "z".

sizzzzlerz
A: 

I'd suggest don't use macro for such functions. C99 supports inline functions just write

inline char *_hex(char c)
{
   ... write there what you need in readable form ...
}
Artyom
+1  A: 

You have made the same error in your test loop as you did in the macro.

for(a = "a" ; a < "z";a++){

should be:

for(a = 'a' ; a < 'z'; a++){

And of course the sensible solution is to use isxdigit() defined in ctype.h as a macro (so you could take a look if you are interested).

Clifford