I'm wondering if anyone could explain how a couple statements in this code works.
Code:
int main()
{
char c, c1, c2;
printf("enter your sentence\n");
while( (c = getchar()) != EOF ){
if( c == '%' ){
c1 = getchar();
c2 = getchar();
if( c1 == EOF || c2 == EOF ) exit(0);
c1 = tolower(c1);
c2 = tolower(c2);
if( ! isxdigit(c1) || ! isxdigit(c2) ) exit(0);
if( c1 <= '9' )
c1 = c1 - '0';
else
c1 = c1 - 'a' + 10;
if( c2 <= '9' )
c2 = c2 - '0';
else
c2 = c2 - 'a' + 10;
putchar( 16 * c1 + c2 );
} else if( c == '+' )
putchar(' ');
else
putchar(c);
}
exit(0);
}
===============================================
int main()
{
int c;
char *h = "0123456789abcdef";
while( (c = getchar()) != EOF ){
if( 'a' <= c && c <= 'z'
|| 'A' <= c && c <= 'Z'
|| '0' <= c && c <= '9'
|| c == '-' || c == '_' || c == '.' )
putchar(c);
else if( c == ' ' )
putchar('+');
else {
putchar('%');
putchar(h[c >> 4]);
putchar(h[c & 0x0f]);
}
}
exit(0);
}
I know what the code does I've worked several examples, but I'm a bit unsure how it works specifically.
Code:
if( ! isxdigit(c1) || ! isxdigit(c2) ) exit(0);
if( c1 <= '9' )
c1 = c1 - '0';
else
c1 = c1 - 'a' + 10;
if( c2 <= '9' )
c2 = c2 - '0';
else
c2 = c2 - 'a' + 10;
putchar( 16 * c1 + c2 );
why is there a ! in the isxdigit(c1) statement?
and how does comparing '0' and 'a' and '9' in the if else statements change a Hex value to ASCII?
My other question is in the second part
Code:
putchar(h[c >> 4]);
putchar(h[c & 0x0f]);
I don't understand how these two statements function why is there >> and & in them? I've seen them used for nibble operations in microcontrollers but I'm confused what they are doing here. Thank you very much.