您的位置:首页 > 产品设计 > UI/UE

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

2006-01-05 11:53 661 查看
/*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
=='/0')
break;
if (hexStg
> 0x29 && hexStg
< 0x40 ) //if 0 to 9
digit
= hexStg
& 0x0f; //convert to int
else if (hexStg
>='a' && hexStg
<= 'f') //if a to f
digit
= (hexStg
& 0x0f) + 9; //convert to int
else if (hexStg
>='A' && hexStg
<= 'F') //if A to F
digit
= (hexStg
& 0x0f) + 9; //convert to int
else break;
n++;
}
count = n;
m = n - 1;
n = 0;
while(n < count) {
// digit
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
<< (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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: