J
James Brown
All,
I have a series of characters which I need to convert to integer values.
Each character is read in turn from a function 'nextch', and hex-digits are
identified by the isxdigit function - so I'm looking at '0' - '9', 'A' - 'Z'
and 'a' - 'z'.
Here is what I've got:
int num = 0;
int ch = nextch(); /* nextc obtains the next character value */
while(isxdigit(ch))
{
if(isdigit(ch))
ch = ch - '0'; /* this is portable I believe */
else
ch = (ch & ~0x20) - 'A' + 10; /* not sure if this is ok */
num = num * 0x10 + ch;
ch = nextch();
}
If you look at the if-else statement inside the while() loop, you will see
how I attempt to convert 'ch' from a character-value to a numeric value in
the range 0-15 inclusive. But I have doubts about the ((ch & ~0x20) - 'A' +
10) expression:
It assumes that 'A' - 'F' are consecutive values
It assumes that 'a' - 'f' are consecutive, and are always 0x20 above their
'uppercase' counterparts.
Are these assumptions correct? I'm guessing the code is non-portable, so
does anyone have a neat(er) suggestion?
p.s. I derived this code from the lcc compiler sourcecode...
James
I have a series of characters which I need to convert to integer values.
Each character is read in turn from a function 'nextch', and hex-digits are
identified by the isxdigit function - so I'm looking at '0' - '9', 'A' - 'Z'
and 'a' - 'z'.
Here is what I've got:
int num = 0;
int ch = nextch(); /* nextc obtains the next character value */
while(isxdigit(ch))
{
if(isdigit(ch))
ch = ch - '0'; /* this is portable I believe */
else
ch = (ch & ~0x20) - 'A' + 10; /* not sure if this is ok */
num = num * 0x10 + ch;
ch = nextch();
}
If you look at the if-else statement inside the while() loop, you will see
how I attempt to convert 'ch' from a character-value to a numeric value in
the range 0-15 inclusive. But I have doubts about the ((ch & ~0x20) - 'A' +
10) expression:
It assumes that 'A' - 'F' are consecutive values
It assumes that 'a' - 'f' are consecutive, and are always 0x20 above their
'uppercase' counterparts.
Are these assumptions correct? I'm guessing the code is non-portable, so
does anyone have a neat(er) suggestion?
p.s. I derived this code from the lcc compiler sourcecode...
James