十六进制字符串转ASCII

之前用网上的代码,直到有一天遇到了问题,决定添加异常判断(因为这个问题找了好几天才发现原因)。

1.添加对输入字符串合法性判断(可以根据个人需要更改)

2.添加输出内存字节判断防止越界。

void HexStringToASCII(const std::string & strInput, char * pOutput, int iOutPutSize)
{
	if (strInput.size() % 2 != 0)
		return;
	if (strInput.size() / 2 > iOutPutSize)
		return;
	for (std::string::size_type i = 0; i < strInput.size(); i+=2)
	{
		int n = i / 2;
		if (strInput[i] >= '0' && strInput[i] <= '9')
			pOutput[n] = (strInput[i] - '0') << 4;
		else if (strInput[i] >= 'A' && strInput[i] <= 'F')
			pOutput[n] = (strInput[i] - 'A' + 10) << 4;
		else if (strInput[i] >= 'a' && strInput[i] <= 'f')
			pOutput[n] = (strInput[i] - 'a' + 10) << 4;
		else
			return;
		if (strInput[i+1] >= '0' && strInput[i+1] <= '9')
			pOutput[n] |= (strInput[i+1] - '0');
		else if (strInput[i+1] >= 'A' && strInput[i+1] <= 'F')
			pOutput[n] |= (strInput[i+1] - 'A' + 10);
		else if (strInput[i+1] >= 'a' && strInput[i+1] <= 'f')
			pOutput[n] |= (strInput[i+1] - 'a' + 10);
		else
			return;
	}
}

你可能感兴趣的:(类型转换,c,类型转换,十六进制,异常处理)