字符串转16进制 str2hex

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#include <ctype.h>

void StrToHex(unsigned char *pbDest, unsigned char *pbSrc, int nLen)

{

    char h1,h2;

    unsigned char s1,s2;

    int i;



    for (i=0; i<nLen; i++)

        {

            h1 = pbSrc[2*i];

            h2 = pbSrc[2*i+1];



            s1 = toupper(h1) - 0x30;

            if (s1 > 9)

                s1 -= 7;



            s2 = toupper(h2) - 0x30;

            if (s2 > 9)

                s2 -= 7;



            pbDest[i] = s1*16 + s2;

        }

}



int main()

{

    int i;

    unsigned char tmp[] = "AA5539200000";

    unsigned char out[1024] = {0};

    unsigned char arr[1024]={0};

    char * temp=arr;



    memset(out, 0 ,1024);

    printf("tmp:%s\r\n",tmp);

    printf("sizeof(tmp)=%d\r\n",(int)sizeof(tmp));

    StrToHex(out, tmp, (sizeof(tmp)-1)/2);

    

    int len=0;



    for(i=0; i<sizeof(tmp)/2; i++)

    {

        printf("out[%d] : %02X \n", i, out[i]);

        len+=sprintf(temp+len,"%02X",out[i]);

    }



    printf("temp:%s\r\n",temp);



    return 0;

}

 

posted @ 2020-06-03 17:27  HuDaXia  阅读(1862)  评论(0编辑  收藏  举报