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

要求:
char cArr[20] = “a1b2c3d4e5f6”; //字符个数双数,小写
char cBrr[6] = {0xa1, 0xb2, 0xc3, 0xd4, 0xe5, 0xf6};

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

unsigned int persist_ssl_hashKeyConvert(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 
		{
			cTempor = 0xa + (*pUserInput - 'a');
		}
		
		pKeyArray[i] = cTempor;
		pUserInput++;
		
		if (*pUserInput >= '0' && *pUserInput <= '9')
		{
			cTempor = *pUserInput - 48;
		}
		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;
	
	persist_ssl_hashKeyConvert(cArr, ucBrr);
	
	printf("cArr = %s\n", cArr);
	printf("ucBrr =\n");
	for (i = 0; i < sizeof(ucBrr); i++)
	{
		printf("%x", ucBrr[i]>>4);
		printf("%x", ucBrr[i] & 0x0f);
		printf(" ");
	}
	puts("");
  
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wanggong_1991/article/details/88420307