[C Language Utility]Convert Hex String to string represented by its corresponding Hex Values

    技术2022-05-11  63

    /*For example*Hex String: *       unsigned char *src="0a0b0c0d"*Converted String: *       unsigned char *des={0x0a,0x0b,0x0c,0x0d}*Reference:*       http://bdn.borland.com/article/0,1410,17203,00.html*/

    #include "stdafx.h"#include <iostream.h>#include <string.h>

    int axtoi(char *hexStg) {  int n = 0;         // position in string  int m = 0;         // position in digit[] to shift  int count;         // loop index  int intValue = 0;  // integer value of hex string  int digit[5];      // hold values to convert  while (n < 4) {     if (hexStg[n]=='/0')        break;     if (hexStg[n] > 0x29 && hexStg[n] < 0x40 ) //if 0 to 9        digit[n] = hexStg[n] & 0x0f;            //convert to int     else if (hexStg[n] >='a' && hexStg[n] <= 'f') //if a to f        digit[n] = (hexStg[n] & 0x0f) + 9;      //convert to int     else if (hexStg[n] >='A' && hexStg[n] <= 'F') //if A to F        digit[n] = (hexStg[n] & 0x0f) + 9;      //convert to int     else break;    n++;  }  count = n;  m = n - 1;  n = 0;  while(n < count) {     // digit[n] is value of hex digit at position n     // (m << 2) is the number of positions to shift     // OR the bits into return value     intValue = intValue | (digit[n] << (m << 2));     m--;   // adjust the position to set     n++;   // next digit to process  }  return (intValue);}

    void convert(char * src,long src_len,char * des,long *des_len)

    {

          char tempStr[4]={0};

         *des_len=src_len>>2;

           for(int i=0;i<(*des_len);i++)

           {

                  strncpy(tempStr,src+i*2,2);

                  des[i] =(char)axtoi(tempStr);

          }

    }

    int main() {     char src[20]="01020304aa";  char supposed_des[10]={0x01,0x02,0x03,0x04,0xaa};

     char des[10]={0};    long des_len=0;

     convert(src,10,des,&des_len);

        if(0==memcmp(des,supposed_des,des_len))  cout<<"Successful!"<<endl; else  cout<<"Failed!/n"<<endl;

        return 0;}


    最新回复(0)