/*
例如:“7F” 转成 整数0x7F
*/
#include <stdio.h>
/**
*******************************************************************************
* @brief ASCII转十六进制数 函数
* @param [in] *str 字符串指针
* @param [in] size 要转换的字符个数
* @param [in] *result 转换结果指针
* @return None
* @note
*******************************************************************************
*/
void AsciiToHex(char *str, unsigned char size, unsigned char *result)
{
unsigned char tmp;
for(*result = 0; size; size--, str++)
{
if(('9' >= *str) && (*str >='0') ) tmp = *str - '0';
else if(('F' >= *str) && (*str >='A') ) tmp = *str - 'A' + 10;
else if(('f' >= *str) && (*str >='a') ) tmp = *str - 'a' + 10;
*result |= tmp<<((size-1)*4);
}
}
/**
*******************************************************************************
* @brief 主 函数
* @param [in] None
* @return None
* @note
*******************************************************************************
*/
int main(void)
{
char a[] = "7F";
unsigned char result;
AsciiToHex(a, 2, &result);
printf("result = %x \n", result);
printf("result = %d \n", result);
}
运行结果: