/********************************************************************************
* @file str_hex.c
* @author jianqiang.xue
* @Version V1.0.0
* @Date 2021-04-27
* @brief NULL
********************************************************************************/
/* Includes ------------------------------------------------------------------*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
/* Public function prototypes -----------------------------------------------*/
/**
* @brief 字符串转16进制值
* @param str: 16进制字符串(低位在前) 比如:0x1234,则输入"3412", 然后输出 0x1234
* @param out: 16进制数字存放的数组
* @retval 输出数组长度
*/
uint8_t str_to_hex(char *str, uint8_t *out)
{
char *p = str;
char high = 0, low = 0;
uint8_t tmplen = strlen(p), cnt = 0;
tmplen = strlen(p);
while (cnt < (tmplen / 2))
{
high = ((*p > '9') && ((*p <= 'F') || (*p <= 'f'))) ? *p - 48 - 7 : *p - 48;
low = (*(++p) > '9' && ((*p <= 'F') || (*p <= 'f'))) ? *(p)-48 - 7 : *(p)-48;
out[cnt] = ((high & 0x0f) << 4 | (low & 0x0f));
p++;
cnt++;
}
if (tmplen % 2 != 0)
{
out[cnt] = ((*p > '9') && ((*p <= 'F') || (*p <= 'f'))) ? *p - 48 - 7 : *p - 48;
}
return (tmplen / 2 + tmplen % 2);
}
/**
* @brief 字节值转字符串 0x1234 -> "1234"
* @note NULL
* @param *dest: 存放转换后的字符串
* @param *source: 需要转换的缓存区
* @param sourceLen: 需要转换的字节长度
* @retval None
*/
void byte_to_string(uint8_t *dest, uint8_t *source, int sourceLen)
{
uint8_t i = 0;
uint8_t highByte = 0, lowByte = 0;
uint8_t temp[6] = {0};
for (i = 0; i < sourceLen; i++)
{
highByte = source[i] >> 4;
lowByte = source[i] & 0x0f;
highByte += 0x30;
if (highByte > 0x39)
temp[i * 2] = highByte + 0x07;
else
temp[i * 2] = highByte;
lowByte += 0x30;
if (lowByte > 0x39)
temp[i * 2 + 1] = lowByte + 0x07;
else
temp[i * 2 + 1] = lowByte;
}
memcpy(dest, temp, 2 * sourceLen);
}
/********************************************************************************
* @file str_hex.h
* @author jianqiang.xue
* @Version V1.0.0
* @Date 2021-04-27
* @brief NULL
********************************************************************************/
#ifndef __STR_HEX_H
#define __STR_HEX_H
#include <stdint.h>
uint8_t str_to_hex(char *str, uint8_t *out);
void byte_to_string(uint8_t *dest, uint8_t *source, int sourceLen);
#endif