C:字符串和十六进制转换

源码:

#include 
#include 
#include 

/* 字符串转换成16进制 */
inline char *Str2Hex(char* pOut, const char* pInput, const int nInLen)
{
	const char* chHexList = "0123456789ABCDEF";
	int nIndex = 0;
	int i=0, j=0;
	for (i=0, j=0; i>4) & 0xf);
			pOut[i*2] = chHexList[nIndex];
		}
	return pOut;
}

/* 16进制转换成字符串 */
inline char *Hex2Str(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;
}

int main()
{	
	char *str = "AdamsKen";
	/* 是字符串中字符个数的两倍,注意大小是否够用 */
	char hex[20]={0};
	printf("str : %s \n", str);
	
	/* 字符串转为十六进制 */
	Str2Hex(hex, str, strlen(str));
	printf("hex : %s \n", hex);
	
	/*str2 必须是数组,不能是字符串*/
	char str2[10] = {0};
	int nLen = strnlen(hex, sizeof(hex));
	
	/* printf("nLen : %d \n", nLen); */
	
	/* 十六进制转为字符串 */
	Hex2Str(str2, hex, nLen);
	printf("str2 : %s \n", str2);
	
	return 0;
}

运行测试:

root@ubuntu:/mnt/hgfs/Ubuntu12.04-share/03_test/01_C/2_file# ./9
str : AdamsKen 
hex : 4164616D734B656E 
str2 : AdamsKen 
root@ubuntu:/mnt/hgfs/Ubuntu12.04-share/03_test/01_C/2_file# 

和下表相对应:(小写的s: 73H )
C:字符串和十六进制转换_第1张图片

Ps:
程序不是自己写的,抄人家的。扎心。

参考链接:
https://blog.csdn.net/woxiaozhi/article/details/48339003?utm_source=blogxgwz5

https://blog.csdn.net/wangzhyy/article/details/78720514

你可能感兴趣的:(C/C++)