搜尋此網誌

2013年2月28日 星期四

Str processing functions --(1)

/*Translate str(decimal) to unsigned long value.*/
unsigned long str_to_dec_u32(char *Strbuf, unsigned long *pSUM)

{
if ((*Strbuf >= 0x30) && (*Strbuf <= 0x39)) {
unsigned long ReturnValue = str_to_dec_u32((Strbuf + 1),pSUM);
*pSUM += (*Strbuf % 0x10) * ReturnValue;
return ReturnValue * 10;
}
else {
*pSUM = 0;
return 1;
}
}


/*Translate str(hexadecimal) to unsigned long value.*/
unsigned long str_to_hex_u32(char *Strbuf, unsigned long *pSUM)

{
if ((*Strbuf >= '0') && (*Strbuf <= '9')) {
unsigned long ReturnValue = str_to_hex_u32((Strbuf + 1), pSUM);
*pSUM += (*Strbuf - 0x30) * ReturnValue;
return ReturnValue * 0x10;
} else if ((*Strbuf >= 'a') && (*Strbuf <= 'f')) {
unsigned long ReturnValue = str_to_hex_u32((Strbuf + 1), pSUM);
*pSUM += (*Strbuf - 0x57) * ReturnValue;
return ReturnValue * 0x10;
} else if ((*Strbuf >= 'A') && (*Strbuf <= 'F')) {
unsigned long ReturnValue = str_to_hex_u32((Strbuf + 1), pSUM);
*pSUM += (*Strbuf - 0x37) * ReturnValue;
return ReturnValue * 0x10;
} else {
*pSUM = 0;
return 1;
}
}

/*count str length.*/
int strlen(const char *s)

{
const char *sc;

for (sc = s; *sc != '\0'; ++sc)
/* nothing */;
return (int)(sc - s);
}


/**
 * strstr - Find the first substring in a %NUL terminated string
 * @s1: The string to be searched
 * @s2: The string to search for
 */
char *strstr(const char *s1, const char *s2)
{
int l1, l2;

l2 = strlen(s2);
if (!l2)
return (char *)s1;
l1 = strlen(s1);
while (l1 >= l2) {
l1--;
if (!memcmp(s1, s2, l2))
return (char *)s1;
s1++;
}
return NULL;
}


/*Check whether it is decimal.*/
unsigned char str_isdigit(char *str_buf)
{
    int i;
    for (i = 0; i < strlen(str_buf); i++) {
        if(!((*(str_buf + i) >= '0') && (*(str_buf + i) <= '9')))
            return 0;
    }
    return 1;
}

/*Check whether it is hexadecimal.*/
unsigned char str_isxdigit(char *str_buf)
{
    int i;
    for (i = 0; i < strlen(str_buf); i++) {
        if(!(
        ((*(str_buf + i) >= '0') && (*(str_buf + i) <= '9'))
        || ((*(str_buf + i) >= 'a') && (*(str_buf + i) <= 'f'))
        || ((*(str_buf + i) >= 'A') && (*(str_buf + i) <= 'F'))
        ))
            return 0;
    }
    return 1;
}

/*Translate str(decimal or hexadecimal) to unsigned long value.*/
int str_to_u32(char *Strbuf, unsigned long *pSUM)
{
unsigned long temp_u32;
char *str = Strbuf;
if ((str[0] == '0') && ((str[1] == 'x') || (str[1] == 'X'))) {
str = &str[2];
if (str_isxdigit(str)) {
str_to_hex_u32(str, &temp_u32);
*pSUM = temp_u32;
} else {
return 0x01;
}
} else {
if (str_isdigit(str)) {
str_to_dec_u32(str, &temp_u32);
*pSUM = temp_u32;
} else {
return 0x01;
}
}
return 0x00;
}

沒有留言:

張貼留言