C语言 十六进制字符串和十六进制之间互转(嵌入式编程)

type.c

/*
 * Module Name:  type.c
 * Module Date:  2019-7-20
 * Module Auth:  zhangpeng
 * Description:  存放一些通用的函数
 * Others:
 * Revision History:
 * Date Rel Ver Notes
 * 2019-7-20 11:30:12  新建文件
 */
 

#include "board.h"
#include <ctype.h>
// -----------------------------------------------------------------
// 函数功能: 判断字符串s是否包含c
// 函数名称: str_is_include
// 参数1   : s 源字符串
// 参数2   : c 目标字符串
// 返回值  : [1] 包含 [其他值] 不包含
// -----------------------------------------------------------------
int str_is_include (char *s, char *c)
{
	int i = 0, j = 0, flag = -1;
	while (i < strlen (s) && j < strlen (c))
	{
		if (s[i] == c[j]) //如果字符相同则两个字符都增加
		{
			i++;
			j++;
		}
		else
		{
			i = i - j + 1; //主串字符回到比较最开始比较的后一个字符
			j = 0;   //字串字符重新开始
		}
		if (j == strlen (c)) //如果匹配成功
		{
			flag = 1; //字串出现
			break;
		}
	}
	return flag;
}
// -----------------------------------------------------------------
// 函数功能: 字节数组转字符串类型
// 函数名称: hexbyte_to_hex_str
// 参数1   : src 源字符串
// 参数2   : obj 目标字节数组
// 说明    : {0x01,0x03,0x03,x04} --> "01020304"
// 返回值  : 1 成功
// -----------------------------------------------------------------
static int hexbyte_to_hex_str (char *src, char *obj, uint16_t length)
{
	for (int i = 0; i < length; i++)
	{
		sprintf (obj, "%02X", src[i]);
		obj += 2;
	}
	return 1;
}
// -----------------------------------------------------------------
// 函数功能: hex字符串转byte数组
// 函数名称: hexbyte_to_hex_str
// 参数1   : src 源字符串
// 参数2   : obj 目标字节数组
// 说明    : "01020304" --> {0x01,0x03,0x03,x04} 或 "01 02 03 04"->{0x01,0x03,0x03,x04}
// 返回值  : 1 成功
// -----------------------------------------------------------------
static int hexstr_to_hexbyte (char *src, char *obj, uint16_t length)
{
	char h1, h2;
	uint8_t  s1, s2;
	int i;

	for (i = 0; i < length; i++)
	{
		h1 = src[2 * i];
		h2 = src[2 * i + 1];

		s1 = toupper (h1) - 0x30;
		if (s1 > 9)
			s1 -= 7;
		s2 = toupper (h2) - 0x30;
		if (s2 > 9)
			s2 -= 7;
		obj[i] = s1 * 16 + s2;
	}
	return 1;
}

// 函数封装
TypeFunc_t TypeFunc =
{
	hexbyte_to_hex_str, //HexToStr
	hexstr_to_hexbyte,  //StrToHex
};

type.h

#ifndef _TYPE_H
#define _TYPE_H
#include <stdint.h>
typedef struct TypeFunc_t
{
	int (*HexToStr)(char *,char *,uint16_t);
	int (*StrToHex)(char *,char *,uint16_t);
}TypeFunc_t;
extern TypeFunc_t TypeFunc;
#endif 
如果这篇文章对您很有帮助,不妨
----- 本文结束 ❤ 感谢您的阅读 ----