|
楼主 |
发表于 2012-12-13 09:53:38
|
显示全部楼层
自己回复给自己。只用《C程序设计语言》第一二章的内容
#include <stdio.h>
#define YES 1
#define NO 0
#define HEXL 2
#define FHEX 6
#define MAXWORD 1000
char s[MAXWORD];
char c[HEXL+1];
int err;
int htoi(char c[HEXL+1]);
int ten(int i);
main ()
{
int i, j;
int r, g, b;
err = YES;
for (i = 1; (s[i] = getchar()) != EOF; ++i){
while (s[i] == '\n'){
s[i] = '\0';
--i;
if (i == FHEX){
i = 1;
r = ten(i);
i = i + HEXL;
g = ten(i);
i = i + HEXL;
b = ten(i);
if (err == NO){
printf("Forbidden character! Please resume load.\n");
err = YES;
break;
}
printf("R:%d,G:%d,B:%d\n", r, g, b);
}else{
printf("Input error! Please resume load.\n");
}
for ( ; i > 0; --i)
s[i] = '\0';
break;
}
}
return 0;
}
/* htoi: convert hexadecimal string s to integer */
int htoi(char s[])
{
int hexdigit, i, inhex, n;
i = 0;
if (s[i] == '0'){ /* skip optional 0x or 0X */
++i;
if (s[i] == 'x' || s[i] == 'X')
++i;
}
n = 0; /* integer value to be returned */
inhex = YES; /*assume valid hexadecimal digit*/
for (; inhex == YES; ++i){
if (s[i] >= '0' && s[i] <= '9')
hexdigit = s[i] - '0';
else if (s[i] >= 'a' && s[i] <= 'f')
hexdigit = s[i] - 'a' + 10;
else if (s[i] >= 'A' && s[i] <= 'F')
hexdigit = s[i] - 'A' + 10;
else{
inhex = NO;/* not a valid hexadecimal digit */
if (i <= HEXL-1)
err = NO;
}
if (inhex == YES)
n = 16*n+hexdigit;
}
return n;
}
int ten(int i)
{
int j;
for (j = 0; j < HEXL; ++j){
c[j] = s[i];
++i;
}
return htoi(c);
}
|
|