#include <stdio.h>
#include <unistd.h>
#include <string.h>
//字符串转换成16进制
inline char *CharArrayToHexString(char* pOut, const int nMaxLen, const char* pInput, const int nInLen)
{
const char* chHexList = "0123456789ABCDEF";
int nIndex = 0;
int i=0, j=0;
for (i=0, j=0;i<nInLen;i++, j+=2)
{
nIndex = (pInput[i] & 0xf);
pOut[i*2+1] = chHexList[nIndex];
nIndex = ((pInput[i]>>4) & 0xf);
pOut[i*2] = chHexList[nIndex];
}
return pOut;
}
//16进制转换成字符串 方法1
inline char *HexStringToCharArray(char* pOut, const char* pInput, const int nInLen)
{
int i=0;
int tc;
for (i = 0; i < nInLen/2 ; i++)
{
sscanf(pInput+i*2, "%02X", (unsigned int*)(pOut+i));
}
pOut[i] = '\0';
return pOut;
}
//16进制转换成字符串 方法2
char a2x(char ch)
{
switch(ch)
{
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
case 'A':
case 'a':
return 10;
case 'B':
case 'b':
return 11;
case 'C':
case 'c':
return 12;
case 'D':
case 'd':
return 13;
case 'E':
case 'e':
return 14;
case 'F':
case 'f':
return 15;
default:
break;;
}
return 0;
}
int main()
{
char szTmp[9] = "99990198";
char szHex[20] = {0};
char szAfter[9] = {0};
int i = 0;
memset(szAfter, 0, sizeof(szAfter));
int nLen = strnlen(szTmp, sizeof(szTmp));
CharArrayToHexString(szHex, (int)sizeof(szHex), szTmp, nLen);
nLen = 2*nLen;
szHex[nLen] = '\0';
printf("szHex:%s \n\n", szHex);
#if 1
HexStringToCharArray(szAfter, szHex, nLen);
#else
while(szHex[i])
{
szAfter[i >> 1] = (a2x(szHex[i]) << 4) | a2x(szHex[i + 1]);
i += 2;
}
szAfter[i >> 1] = '\0';
#endif
printf("szAfter:%s \n\n", szAfter);
return 0;
}
运行结果:
szHex:3939393930313938
szAfter:99990198