C语言字符串转换为十六进制字符数组

  • Post author:
  • Post category:其他


要求:

char cArr[20] = “a1b2c3d4e5f6”; //字符个数双数

char cBrr[6] = {0xa1, 0xb2, 0xc3, 0xd4, 0xe5, 0xf6};

调用函数,参数1传入cArr, 参数2传入cBrr

unsigned int my_func(char *pUserInput, unsigned char *pKeyArray)
{
	if (NULL == pUserInput || NULL == pKeyArray)
	{
			return 0;
	}
	
	unsigned int uiKeySize = strlen(pUserInput) / 2;
	int i = 0;
	char cTempor = 0;
	
	while(i < uiKeySize)
	{
		if (*pUserInput >= '0' && *pUserInput <= '9')
		{
			cTempor = *pUserInput - 48;
		}
		else if (*pUserInput >= 'a' && *pUserInput <= 'z') 
		{
			cTempor = 0xa + (*pUserInput - 'a');
		}
		else 
		{
			cTempor = 0xa + (*pUserInput - 'A');
		}
		
		pKeyArray[i] = cTempor;
		pUserInput++;
		
		if (*pUserInput >= '0' && *pUserInput <= '9')
		{
			cTempor = *pUserInput - 48;
		}
		else if (*pUserInput >= 'a' && *pUserInput <= 'z') 
		{
			cTempor = 0xa + (*pUserInput - 'a');
		}
		else 
		{
			cTempor = 0xa + (*pUserInput - 'A');
		}
		
		pKeyArray[i] = (pKeyArray[i] << 4) | cTempor;
		pUserInput++;
		i++;
	}
	
	return uiKeySize;	
}

int main()
{
	char cArr[] = "41a65db35c069fbfc412be4f73223e007332ba32cc3768a23d9f971960aa6744";  //字符个数双数,小写
	unsigned char ucBrr[32];
	int i;
	
	my_func(cArr, ucBrr);
	
	printf("cArr = %s\n", cArr);
	printf("ucBrr =\n");
	for (i = 0; i < sizeof(ucBrr); i++)
	{
		printf("%x", ucBrr[i]);
		printf(" ");
	}
	puts("");
  
	return 0;
}



版权声明:本文为wanggong_1991原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。