C语言中HEX转ASCII函数,ASCII转HEX函数,ASCII转DEC函数,四字节大小端转换函数整理

人生第一次写博客,工作几年,现在才想起来应该写点东西留点纪念,亡羊补牢,犹未为晚吧,渐渐把一些重要知识点整理起来,万事开头难,所以第一篇就整理几个转换函数,项目开发中总结的,编写者不知呀╮(╯▽╰)╭,感谢无名者,已实际应用,这几个函数C语言中挺常用的,在单片机开发中也特别常用,特别是需要字符显示数据的时候,废话少说~~~~

第一个,HEX转ASCII函数如下:

int HexToAscii(unsigned char *pHexStr,unsigned char *pAscStr,int Len)
{
	char Nibble[2];
	unsigned char Buffer[2048];
	int i = 0;
	int j = 0;

	for(i=0;i> 4 & 0X0F;
		Nibble[1]=pHexStr[i] & 0x0F;
		for(j=0;j<2;j++)
		{
			if(Nibble[j]<10)
			{
				Nibble[j]=Nibble[j]+0x30;
			}
			else if(Nibble[j]<16)
			{
				Nibble[j]=Nibble[j]-10+'A';
			}
			else
			{
				return 0;
			}
		}
		memcpy(Buffer+i*2,Nibble,2);
	}
	Buffer[2*Len]=0x00;
	memcpy(pAscStr,Buffer,2*Len);
	pAscStr[2*Len]=0x00;
	return 1;
}
}

第二个,ASCII转HEX函数如下:

char  AsciiToHex(unsigned char * pAscii, unsigned char * pHex, int nLen)
{
	int nHexLen = nLen / 2;
	unsigned char Nibble[2] = {0};
	int i = 0;
	int j = 0;

	if (nLen%2)
	{
		return 1;
	}

	for (i = 0; i < nHexLen; i ++)
	{
		Nibble[0] = *pAscii ++;		
		Nibble[1] = *pAscii ++;
		for (j = 0; j < 2; j ++)
		{
			if (Nibble[j] <= 'F' && Nibble[j] >= 'A')
				Nibble[j] = Nibble[j] - 'A' + 10;
			else if (Nibble[j] <= 'f' && Nibble[j] >= 'a')
				Nibble[j] = Nibble[j] - 'a' + 10;
			else if (Nibble[j] >= '0' && Nibble[j] <= '9')
				Nibble [j] = Nibble[j] - '0';
			else
				return 1;//Nibble[j] = Nibble[j] - 'a' + 10;
			
		}	// for (int j = ...)
		pHex[i] = Nibble[0] << 4;	// Set the high nibble
		pHex[i] |= Nibble[1];	//Set the low nibble
	}	// for (int i = ...)
	return 0;
}

第三个,ASCII转DEC函数如下:

char  AsciiToDec(unsigned char * pAscii, unsigned char * pHex, int nLen)
{
	int nHexLen = nLen / 2;
	unsigned char Nibble[2] = {0};
	int i = 0;
	int j = 0;

	if (nLen%2)
	{
		return 1;
	}

	for (i = 0; i < nHexLen; i ++)
	{
		Nibble[0] = *pAscii ++;		
		Nibble[1] = *pAscii ++;
		for (j = 0; j < 2; j ++)
		{
			Nibble [j] = Nibble[j] - '0';
		}	// for (int j = ...)
	
		pHex[i] = Nibble[0] * 10;	// Set the high nibble
		pHex[i] += Nibble[1];	//Set the low nibble
	}	// for (int i = ...)
	return 0;
}

第四个,四字节大小端转换函数:

#define REVERSE(a) (((a) & 0xff) << 24 | ((a) & 0xff00) << 8 | ((a) & 0xff0000) >> 8 | ((a) & 0xff000000) >> 24)
//32位数据四个字节大小端转换

以上就是本次总结的几个函数,希望有需要的人可以拿去用。

你可能感兴趣的:(C语言开发)