加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

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

(2011-05-03 17:22:57)
标签:

杂谈

分类: 编程方法

  今天在测试生产系统的时候,需要输入测试数据,网上没有找到可用的代码,自己写了一个,有需要的可以使用一下。

  在网络通信中,服务端收到的内容都是以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;
 }
}

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有