您的位置:首页 > 编程语言 > C语言/C++

C语言数字字符串转换为十六进制格式函数

2014-07-03 14:36 225 查看
今天在测试生产系统的时候,需要输入测试数据,网上没有找到可用的代码,自己写了一个,有需要的可以使用一下。
在网络通信中,服务端收到的内容都是以16进制存在的8位串,在模拟一个客户端发包的时候,需要将模拟数据转换成16进制。

例如一段数据

char test[]="0000008504050603020101010009011102161400"

要把他转换成

00 00 00 85 04 05 06 03

02 01 01 01 00 09 01 11

02 16 14 00

16进制串。

void CharToHex(char * dest, char * buffer , int len)

{

int i=0;

int j=0;

unsigned char temp;

while(i<len)

{

temp=buffer[i];

if((temp>=0x30)&&(temp<=0x39))

{

temp=temp-0x30;

dest[j]=temp<<4;

}

else if((temp>=0x41)&&(temp<=0x46))

{

temp=temp-0x41+0x0A;

dest[j]=temp<<4;

}

else if((temp>=0x61)&&(temp<=0x66))

{

temp=temp-0x61+0x0A;

dest[j]=temp<<4;

}

else

{

dest[j]=0x00;

}

// dest[j]=dest[j]<<4;

temp=buffer[i+1];

if((temp>=0x30)&&(temp<=0x39))

{

temp=temp-0x30;

dest[j]=dest[j]|temp;

}

else if((temp>=0x41)&&(temp<=0x46))

{

temp=temp-0x41+0x0A;

dest[j]=dest[j]|temp;

}

else if((temp>=0x61)&&(temp<=0x66))

{

temp=temp-0x61+0x0A;

dest[j]=dest[j]|temp;

}

else

{

dest[j]=dest[j]|0x00;

}

i=i+2;

j=j+1;

}

return;

}

附一个十六进制字符串转换的方法。

void HextoString(unsigned char *digest,char* buff,int len) {

unsigned int i;

char *ptr = buff;

for (i = 0; i < len; i++) {

sprintf (ptr,"x", digest[i]);

ptr+=2;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐