C++ 字符串与16进制字符串之间的转换 20
staticintstr_to_hex(char*string,unsignedchar*cbuf,intlen)
{
BYTEhigh,low;
intidx,ii=0;
for(idx=0;idx<len;idx+=2)
{
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<len;i++)
{
sprintf(ptr,"%02x",buf[i]);
ptr+=2;
}
}
扩展资料
byte数组转十六进制字符串
publicstaticStringbyteArraytoHexString(byte[]b){
intiLen=b.length;
StringBuffersb=newStringBuffer(iLen*2);
for(inti=0;i<iLen;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();
}
#include <string>
#include <vector>
#include <sstream>
std::vector<BYTE> str_to_hex(const std::string& str)
{
if (str.size() != str.size() / 2 * 2)
str = "0" + str;
std::vector<BYTE> 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;
}
另一个反过来自己写吧!
自定义的函数的参量和返回值都是string类型的才行啊,你写的返回值不对啊
#include
std::string hex_to_str(const std::vector& vec)
{
std::ostringstream oss;
oss << std::setw(2) << std::setfill('0') << std::hex;
for (auto iter = vec.begin(); iter != vec.end(); ++iter) {
oss << *iter;
}
return oss.str();
}
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/ 参考这里