字符串和16进制整数转换

#include "Inc.h"

int str2char(unsigned char *str,unsigned char* des,int maxsize)
{
    if(maxsize < strlen((char*)str)/2)
        return -1;

    int i,j;
   unsigned char k;
   memset(des,0,maxsize);
    for(i = 0,j=0;i < strlen((char*)str);i++)
    {
        if(str[i]>= '0' && str[i] <= '9')
        {
            k = str[i]  -  '0';
        }else
            if ( (str[i]>= 'A' && str[i] <= 'F' )  )
            {
                    k = str[i] - 'A'+10;
            }
        else  if ( (str[i]>= 'a' && str[i] <= 'f' )  )
             {
                     k = str[i] - 'a'+10;
             }
        else
        {
            return -2;
        }
        if( (i&1) == 0)
            k <<= 4;
        des[j] |= k;
        j += i&1;
    }
    return j;
}
QString char2str(unsigned char * source,int len)
{
    int i =0,j=0;
   // QString str;
   unsigned char t;
   char *str  = new char [len*2+1];
    for(i = 0; i < len; i++)
    {
        t = source[i]>>4;

        if(t >= 0 && t <= 9)
            str[j++] = ( (char)('0'+t) );
        else
            str[j++] =( (char)('A'+t-10) );

        t = source[i] & 0x0f;

        if(t >= 0 && t <= 9)
            str[j++] =( (char)('0'+t) );
        else
             str[j++] = ( (char)('A'+t-10 )  );

    }
    str[j] = 0;
    return QString(str);
}
unsigned short checksum(unsigned short *buf, int nword)
{
    unsigned long sum;

    for(sum = 0; nword > 0; nword--)
        sum += *buf++;

    sum = (sum>>16) + (sum&0xffff);
    sum += (sum>>16);

    return ~sum;
}

阅读更多
文章标签: include
个人分类: tiger_linux
想对作者说点什么? 我来说一句

16进制字符串转整型程序

2010年05月16日 868B 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭