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

來源:互聯網
上載者:User

/*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;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.