But it never seems to want to go into the if statement, even when the MAC address being checked, starts with a 0.
Also I'm pretty sure this is a bad way of doing it, after all all I'm trying to do in this section is check if it is a Hex number or not. If you know a better way could you let me know. (I would still like to know if it's possible to condense that if statement even if I don't use it)
Each char has a value. For example, 'A' is 65, B is '66', 'a' is 97, etc.
Your possible values can be split up in series of characters that follow each other: [0,9], [A,F] and [a,f]. (e.g.: |C| = |A|+2). Using this information, you can check whether your character falls within any of those 3 ranges, using 'only' 6 comparison instead of the 22 you have now.
This won't work because || is logical or, so what you're asking is if MACAddress[i] is equal to any of those characters being true ie. having a non-zero value, which they ALL do, so the statement will always evaluate to true.
You can leave it as it is if it's private implementation type code, as it's quite clear what it does, or else you can call another function that tests the string to see if it is a valid hex number. For example:
int ishex(char* num);
int ishex(char num);
int ishex(char* num) {
int val = 0;
constint base = 16;
for (int i = 0; num[i] != 0; i++) {
int digit;
if ((digit = ishex(num[i])) / base != 0) {
return -i;
}
val *= base;
val += digit;
}
return val;
}
int ishex(char num) {
int val;
switch (num) {
case'0': val = 0; break;
case'1': val = 1; break;
case'2': val = 2; break;
case'3': val = 3; break;
case'4': val = 4; break;
case'5': val = 5; break;
case'6': val = 6; break;
case'7': val = 7; break;
case'8': val = 8; break;
case'9': val = 9; break;
case'A': val = 10; break;
case'B': val = 11; break;
case'C': val = 12; break;
case'D': val = 13; break;
case'E': val = 14; break;
case'F': val = 15; break;
default: val = -16;
}
return val;
}
Which returns the value of the hex string if it succeeds, or else a negative number indicating the position in the string the error occurred. You could modify it to return simply true or false very easily.
Then you can just test: if(ishex(MACAddress) >= 0)
Hope that helps!
@Gaminic: Thanks, I think I'm just gonna leave it the way I have it currently. It's a bit more obvious what I am trying to do my way I think. But thanks for answering, it's good to know for the future.
@Mooncabbage: That is what I had thought (well after I realised it didn't do what I initially thought that it should) but as you say that would mean that it would always go into this if statement, but what I found was that it NEVER went into this if statement, as I said before I'm gonna leave it the way I have it, but if you have any ideas as to what could cause the behaviour I just described, I'd love to know.