C++ 字符串与16进制字符串之间的转换

2025-02-25 20:42:53
推荐回答(3个)
回答1:

staticintstr_to_hex(char*string,unsignedchar*cbuf,intlen)

{

BYTEhigh,low;

intidx,ii=0;

for(idx=0;idx

{

high=string[idx];

low=string[idx+1];

if(high>='0'&&high<='9')

high=high-'0';

elseif(high>='A'&&high<='F')

high=high-'A'+10;

elseif(high>='a'&&high<='f')

high=high-'a'+10;

else

return-1;

if(low>='0'&&low<='9')

low=low-'0';

elseif(low>='A'&&low<='F')

low=low-'A'+10;

elseif(low>='a'&&low<='f')

low=low-'a'+10;

else

return-1;

cbuf[ii++]=high<<4|low;

}

return0;

}

/****************************************************************************

函数名称:hex_to_str

函数功能:十六进制转字符串

输入参数:ptr字符串buf十六进制len十六进制字符串的长度。

输出参数:无

*****************************************************************************/

staticvoidhex_to_str(char*ptr,unsignedchar*buf,intlen)

{

for(inti=0;i

{

sprintf(ptr,"%02x",buf[i]);

ptr+=2;

}

}

扩展资料

byte数组转十六进制字符串

publicstaticStringbyteArraytoHexString(byte[]b){

intiLen=b.length;

StringBuffersb=newStringBuffer(iLen*2);

for(inti=0;i

intintTmp=b[i];

while(intTmp<0){

intTmp=intTmp+256;

}

if(intTmp<16){

sb.append("0");

}

sb.append(Integer.toString(intTmp,16));

}

returnsb.toString().toUpperCase();

}

回答2:

#typedef unsinged char BYTE;
#include
#include
#include

std::vector str_to_hex(const std::string& str)
{
if (str.size() != str.size() / 2 * 2)
str = "0" + str;
std::vector vec;
std::stringstream ss;
ss << std::hex;
for (std::string::size_type ix = 0; ix != str.size() / 2; ++ix) {
int val = 0;
ss << str.substr(ix * 2, 2);
ss >> val;
vec.push_back(val);
ss.clear();
}
return vec;
}

另一个反过来自己写吧!

回答3:

#include
int main()
{
char szValue[] = "0x11";
char ch[32];
int nValude = 0;
sscanf(szValue,"%x",&nValude); //十六进制转数字
sprintf(ch,"%d",nValude); //数字转字符
printf("%d/n",nValude);
return 0;
}
http://baike.baidu.com/view/1364018.htm
http://baike.baidu.com/view/1295144.htm
http://blog.csdn.net/delphiwcdj/article/details/4649854/ 参考这里