VC二进制byte数组转换成对应字符串

/****************************************************************************
函数名称: str_to_hex
函数功能: 字符串转换为十六进制
输入参数: string 字符串 cbuf 十六进制 len 字符串的长度。
输出参数: 无
*****************************************************************************/
int  strtohex(char *string, unsigned char *cbuf, int len)
{
 BYTE high, low;
 int idx, ii=0;
 for (idx=0; idx<len; idx+=2)
 {
  high = string[idx];
  low = string[idx+1];
  
  if(high>='0' && high<='9')
   high = high-'0';
  else if(high>='A' && high<='F')
   high = high - 'A' + 10;
  else if(high>='a' && high<='f')
   high = high - 'a' + 10;
  else
   return -1;
  
  if(low>='0' && low<='9')
   low = low-'0';
  else if(low>='A' && low<='F')
   low = low - 'A' + 10;
  else if(low>='a' && low<='f')
   low = low - 'a' + 10;
  else
   return -1;
  
  cbuf[ii++] = high<<4 | low;
 }
 return 0;
}

/****************************************************************************
函数名称: hex_to_str
函数功能: 十六进制转字符串
输入参数: ptr 字符串 buf 十六进制 len 十六进制字符串的长度。
输出参数: 无
*****************************************************************************/
 void  hextostr(char *ptr,unsigned char *buf,int len)
{
 for(int i = 0; i < len; i++)
 {
  sprintf(ptr, "%02x",buf[i]);
  ptr += 2;
 }
}

 //二进制byte[]数组转换成对应十六进制字符串 
 void btyeTohex(CString& outstr,const  char*  srcbyte, int len)
 { 
 
  //if (len%2!=0)
  //  AfxMessageBox("数组长度必须为偶数!");
  CString t="0123456789ABCDEF";
  int a;
  char ch;     
  int i=0,m=0;
  CString tmp;
  while(i<len)
  {  
   tmp=""; 
   a=srcbyte[i]&0x000f;;
   ch=t[a];
   tmp.Insert(0,ch);        
   a=(srcbyte[i]>>4)&0x000f;;
   ch=t[a];
   tmp.Insert(0,ch);
   outstr+=tmp;  
   i++; 
  }
 
}
//十六进制字符串转换对于二进制byte[]数组
void hexTobtye( char* outbyte,CString& srcstr) 

    CString t="0123456789ABCDEF"; 
    int len=srcstr.GetLength(),k,m,tmp; 
// if (srcstr.GetLength()%2!=0)
//  AfxMessageBox("十六进制字符串位数必须为偶数!");
    m=0;
    for(int i=0;i<len;i++)
    {
  if (m==14)
  {
       //AfxMessageBox("go to 14");
  }
  k=0;
  if((srcstr[i]>='0')&&(srcstr[i]<='9')) k=srcstr[i]-48;
  else if((srcstr[i]>='A')&&(srcstr[i]<='F'))k=srcstr[i]-55; //65
  else if((srcstr[i]>='a')&&(srcstr[i]<='f'))k=srcstr[i]-87; //97
  else{ k=0 ; 
  // AfxMessageBox("sign exist equals 0");
  }; 
  
  if (i%2 !=0)
  {          
      outbyte[m]=((tmp<<4)&0x00f0) |( k&0x00f);
   tmp=0;
   m++;
  }
  else
   tmp= k;
  
    } 
 //  outbyte[m] ='\0';
}


/*
使用方法:
 CString str="616263"; //abc
   char tmp[12];
 hexTobtye(str,tmp);
 CString str1;
 str1=tmp;
 MessageBox(str1);
*/
3. VC二进制byte[]数组转换成对应字符串
 
这个很简单的对c++来说 直接将byte[]数组首地址付给字符串指针
  char tmp[12];
 CString str1;
 str1=tmp;

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值