HEX转BCD ,HEX转ASCII,HEX转DEC 算法合集 | C语言实现

1、HEX与BCD格式相互转换算法

// hex格式转bcd格式
unsigned char HexToBcd(unsigned char hexData)
{
	unsigned char bcdData;
	bcdData = ((hexData / 10) << 4) + (hexData % 10);
	return bcdData;
}

//bcd格式转hex格式
unsigned char BcdToHex(unsigned char bcdData)
{	
	unsigned char hexData;	
	hexData = (bcdData >> 4) * 10 + (bcdData & 0x0F);
	return hexData;
}

2、HEX与ASCII格式相互转换算法

#include 

// 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;
		}
		// Set the high nibble
		pHex[i] = Nibble[0] << 4;
		//Set the low nibble
		pHex[i] |= Nibble[1];	
	}
	return 0;
}


// hex转ascii格式
unsigned char *HexToAscii(unsigned char *pHexStr,unsigned char *pAscStr,uint32_t Len)
{
	char Nibble[2];
	unsigned char Buffer[2048];
	int i = 0;
	int j = 0;

	for(i = 0; i < Len; i++)
	{
		Nibble[0] = pHexStr[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 pAscStr;
}

3、HEX与DEC格式转换

// dec转hex
void DectoHex(int dec, unsigned char *hex, int length) 
{ 
	for(int i=length-1; i>=0; i--) 
	{ 
		hex[i] = (dec%256)&0xFF; 
		dec /= 256; 
	}
}

// hex转dec
unsigned long HextoDec(const unsigned char *hex, int length) 
{ 
	unsigned long rslt = 0; 
	
	for(int i=0; i<length; i++) 
	{ 
		rslt += (unsigned long)(hex[i]) << (8 * (length - 1 - i)); 
	} 
	return rslt; 
}

你可能感兴趣的:(STM32开发,算法,c语言)