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

/*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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值