字符串与十六进制互相转换 vc

本文介绍如何在C++中实现CString类型与十六进制字符串之间的相互转换,包括从CString到十六进制字符串的转换过程及从十六进制字符串到CString的转换方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//字符串CString 转换成CString类型的十六进制串

**********************************************************************************

 CString ConvertCStringoHex(CString Data)
{
//CString转换成char[]
 wchar_t* a=Data.GetBuffer( Data.GetLength() );
 int nLen = WideCharToMultiByte( CP_ACP, 0, a, -1, NULL, 0, NULL, NULL );
 if (nLen == 0)
 {
    return NULL;
 }
 char* pResult = new char[nLen];
 char tagChar[2048];
 WideCharToMultiByte( CP_ACP, 0, a, -1, pResult, nLen, NULL, NULL );
 strncpy( tagChar,pResult , sizeof(tagChar));
    //转换成hex
 CString sResult=L"";
 int nLoop=0;
 while(tagChar[nLoop]!='/0')
 {
  static const char *hex="0123456789ABCDEF";
  if(tagChar[nLoop]<127&&tagChar[nLoop]>0)
  {
   sResult += '0';
   sResult += '0';
   unsigned char chHexA = hex[((unsigned char)(tagChar[nLoop]) >> 4) & 0x0f];
   unsigned char chHexB = hex[(unsigned char)(tagChar[nLoop]) & 0x0f];
            sResult += (char)chHexA;
   sResult += (char)chHexB;
   nLoop++;
  }
  else
  {
    unsigned char chHexA = hex[((unsigned char)(tagChar[nLoop]) >> 4) & 0x0f];
   unsigned char chHexB = hex[(unsigned char)(tagChar[nLoop]) & 0x0f];
   sResult += (char)chHexA;
   sResult += (char)chHexB;

   if(tagChar[++nLoop]=='/0') break;
   sResult+= hex[((unsigned char)(tagChar[nLoop]) >> 4) & 0x0f];
   sResult+=hex[(unsigned char)(tagChar[nLoop]) & 0x0f];
   nLoop++;

  }
 }
    return sResult;

}

 

 

 *********************************************************************************

//十六进制转CString字符串(包括汉字)

CString ConvertHextoCString(CString hex)
{
 CString result=_T("");
 
 char temp[3];
 int i=0;
 if(hex.GetLength()%4!=0)
 {
  return _T("");
 }
 int lenhex=hex.GetLength();
 while(i<lenhex)
 {
  long h4 = CharToHex((long)hex.GetAt(i));
  long h3 = CharToHex((long)hex.GetAt(i+1));

     long h2 = CharToHex((long)hex.GetAt(i+2));
  long h1 = CharToHex((long)hex.GetAt(i+3));
  
  long t1=h4*16+h3;
  long t2=h2*16+h1;
  if(t1==0)
  {
   temp[0]=t2;
   temp[1]='/0';
  }
  else
  {
   temp[0]=t1;
   temp[1]=t2;
   temp[2]='/0';
  }
  i+=4;
  result+=temp;
 } 
 return result;
}

long CharToHex(long ch)
{
 long la = (ch>=(long) 'A' ? (ch -(long) 'A' + 10) : (ch -(long) '0'));
    return la;
}

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值