将将16进制的字符串,两个两个转化为16进制的数值

将将16进制的字符串,两个两个转化为16进制的数值

#include <stdio.h>
#include <string.h>
int sthvalue(char c)
{
    int value;
    if((c>='0')&&(c<='9'))
    {
        value=48;
    }
    else if((c>='a')&&(c<='f'))
    {
        value=87;
    }
    else if((c>='A')&&(c<='F'))
    {
        value=55;
    }
    else
    {
        printf("invalid data %c",c);
        return -1;
    }
    return value;
}
int strtohex(char *a,char *b)
{
    int len=0;
    int sum=0,high=0,low=0,value=0,j=0;
    len=strlen(a);
    printf("%d\n",len);
    for(int i=0;i<len;i++)
    {
        value=sthvalue(a[i]);
        high=(((a[i]-value)&0xF)<<4);
        value=sthvalue(a[i+1]);
        low=((a[i]-value)&0xF);
        sum=high|low;
        j=i/2;
        b[j]=sum;
        i=i++;
    }
    
}
int main()
{  
    char *s="210010c08af870e450";
    char buf1[256]={0};
    int len=0;
    printf("%s\n",s);
    len=strtohex(s,buf1);
    for(int n=0;n<(len/2);n++)
    {
        printf("0x%2x",buf1[n]);
    } 
    puts("");
    return 0;
}

posted on 2023-06-04 20:52  wessf  阅读(18)  评论(0)    收藏  举报