16进制字符串转string
当字符串中有'\0'时⽆法通过tcp将内容发送的客户端,因此需要将原始字符串转换为16进制表⽰的形式然后进⾏发送,发送后要对16进制的字符串进⾏转换,以下代码就是解决16进制转string的。
#include <iostream>
#include <string>
#include <malloc.h>
#include <cstring>
#include <cstdlib>
#include <cstdio>
using namespace std;
char * HexToStr(char *pbSrc, int nLen)
{
char ddl, ddh;
char *pbDest;
pbDest = (char *)malloc(nLen/2+1);
memset(pbDest,0,nLen/2);
int i;
for (i = 0; i <= nLen-2; i+=2)
{
if(pbSrc[i] >= 48 && pbSrc[i] <= 57)
{
ddh = (pbSrc[i]-48)*16;
}
if(pbSrc[i] >= 65 && pbSrc[i] <= 70)
{
ddh = (pbSrc[i] - 55)*16;
}
if(pbSrc[i] >= 97 && pbSrc[i] <= 102)
{
ddh = (pbSrc[i] - 87)*16;
}
if(pbSrc[i+1] >= 48 && pbSrc[i+1] <= 57)
{
ddl = pbSrc[i+1]-48;
}
if(pbSrc[i+1] >= 65 && pbSrc[i+1] <= 70)
{
ddl = pbSrc[i+1] - 55;
}
if(pbSrc[i+1] >= 97 && pbSrc[i+1] <= 102)
{
ddl = pbSrc[i+1] - 87;
}
pbDest[i/2] = ddh+ddl;
}
pbDest[nLen/2+1] = '\0';
return pbDest;
}
int main()
cstring转为int{
char *test = (char *)"68656c6c6f20776f726c64";
char *ptr=nullptr;
ptr = HexToStr(test, 22);
cout << ptr << endl;
free(ptr);
return 0;
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。