0
点赞
收藏
分享

微信扫一扫

C代码_十六进制字符串转字节

你的益达233 2022-04-14 阅读 95
c语言

十六进制字符串转字节数据

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>


/**
* @brief 字符串转字节数组
* @param source 	[IN]字符串指针
* @param dest		[OUT]字节指针
* @param sourceLen	[IN]字符串长度
* @note "1234567890abcdef"-> 12 34 56 78 90 AB CD EF
*/
void StringToByte(char* source, unsigned char* dest, int sourceLen)
{
	int i;
	unsigned char highByte, lowByte;

	for (i = 0; i < sourceLen; i += 2)
	{
		highByte = toupper(source[i]);		//转换为大写
		lowByte  = toupper(source[i + 1]);

		if (highByte > 0x39)
			highByte -= 0x37;
		else
			highByte -= 0x30;

		if (lowByte > 0x39)
			lowByte -= 0x37;
		else
			lowByte -= 0x30;

		dest[i / 2] = (highByte << 4) | lowByte;
	}
	return ;
}



int main(int argc,char*argv[])
{
	int i=0;
	
	char *str="1234567890abcdef";
	int Len = strlen(str);
	unsigned char out[500]={0};
	
	StringToByte(str, out, Len);
	
	printf("Len = %d\n",Len);
	

	printf("out:\n");
	for(i=0;i<Len/2;i++)
	{
		printf("%02X ",out[i]);
	}printf("\n");
	
	
	exit(0);
}

运行结果:

举报

相关推荐

0 条评论