Index:190930-各种进制转换
6.十六进制字符串和十六进制串相互转换
6.1十六进制字符串转十六进制串
(例如"11ff22"- 0x11 0xff 0x22)
#include "Transfer.h"
using namespace std;
string StrToHex(string sHexStr)
{
string StrHex;
const char *ptmp = sHexStr.c_str();
for(int i = 0; i < (sHexStr.size() / 2); ++i)
{
u32 uHightOrder = 0xffffffff;
u32 uLowOrder = 0xffffffff;
if((*ptmp > '0' && *ptmp <= '9') || (*ptmp > 'a' && *ptmp <= 'f') || (*ptmp > 'A' && *ptmp <= 'F') )
{
char acHightOrder[2] = {0};
memcpy(acHightOrder, ptmp, 1);
sscanf(acHightOrder, "%x", &uHightOrder);
ptmp++;
}
if((*ptmp > '0' && *ptmp <= '9') || (*ptmp > 'a' && *ptmp <= 'f') || (*ptmp > 'A' && *ptmp <= 'F') )
{
char acLowOrder[2] = {0};
memcpy(acLowOrder, ptmp, 1);
sscanf(acLowOrder, "%x", &uLowOrder);
ptmp++;
}
if((uHightOrder == 0xffffffff)||(uLowOrder == 0xffffffff))
return "";
u32 uHexTmp = uHightOrder*16 +uLowOrder;
StrHex += (char)uHexTmp;
}
return StrHex;
}
int main(int argc, char const *argv[])
{
string strhex;
strhex = StrToHex("11ff22");
for(int i = 0; i < strhex.size(); ++i)
printf("%x ", (unsigned char)strhex[i]);
puts("");
return 0;
}
输出结果:11 ff 22
6.2十六进制串转十六进制字符串
string HexToStr(string sHexStr)
{
char aStrBuf[sHexStr.size()*2 + 1] = {0};
char *ptmp = aStrBuf;
u32 uoffsset = 0;
memset(aStrBuf, 0, sizeof(aStrBuf));
for(u32 i = 0; i < sHexStr.size(); ++i)
{
snprintf(ptmp, sizeof(aStrBuf) - uoffsset, "%02x", (unsigned char)sHexStr[i]);
ptmp += 2;
uoffsset += 2;
}
string sRetStr = aStrBuf;
return sRetStr;
}
int main(int argc, char const *argv[])
{
string strhex;
strhex = StrToHex("113322");
for(int i = 0; i < strhex.size(); ++i)
printf("%x ", (unsigned char)strhex[i]);
puts("");
strhex = HexToStr(strhex);
for(int i = 0; i < strhex.size(); ++i)
printf("%x ", strhex[i]);
return 0;
}
输出结果:31 31 33 33 32 32
编译:g++ -std=c++11 Transfer2.cpp Transfer.h
[源码入口] 提取码:do39
技术交流QQ群:916932330