BCD编码的数据与基本类型数据之间的转换

/***********************************************************************
BCD编码的数据与基本类型数据之间的转换:
BCD码亦称二进码十进数或二-十进制码,用4位二进数来表示1位十进数中的0~9
这10个数码,8421BCD码是最常用的BCD码,只选用4位二进制码中的前10组代码,
即用0000~1001,来分别表示它所对应的十进制数,而余下的六组代码不用。
************************************************************************/
#include 


unsigned char CharToBCD(unsigned char hex)
{
	unsigned char bcd;
	
	bcd = ((hex>>4) & 0x0F) * 10;
	bcd += hex & 0x0F;
	
	return bcd;
}


unsigned char BCDToChar(unsigned char bcd)
{
	unsigned char hex;
	
	hex = (bcd/10) * 16 + (bcd%10);
	
	return hex;
}


unsigned short BCDToShort(unsigned short bcd)
{
	unsigned short myshort = 0;
	
	myshort = ((bcd>>12) & 0x0F) *1000 + ((bcd>>8) & 0x0F) *100 + ((bcd>>4) & 0x0F) *10 + (bcd & 0x0F);
	
	return myshort;
}


unsigned short ShortToBCD(unsigned short ust)
{
	unsigned short bcd = 0;
	
	bcd = (ust/1000) * 4096 + ((ust%1000)/100) * 256 + ((ust%100)/10) * 16 + (ust%10);
	
	return bcd;
}


unsigned long StringToLong(unsigned char *String)
{
	unsigned long Long;
	
	Long = (String[0]-'0')*10000000+(String[1]-'0')*1000000+(String[2]-'0')*100000+(String[3]-'0')*10000\
		+(String[4]-'0')*1000+(String[5]-'0')*100+(String[6]-'0')*10+(String[7]-'0');
    
	return Long;
}


int main(int argc, char *argv[])
{
	unsigned char src_hex = 0x29;
	unsigned char tar_bcd = 0;
	unsigned char tar_hex = 0;
	
	unsigned short us_src_bcd = 0x4367;
	unsigned short us_tar_bcd = 0;
	unsigned short us_tar_hex = 0;
	
	char str[9] = "12345678";
	unsigned long ul_tar = 0;


	
	tar_bcd = CharToBCD(src_hex);
	printf("src_hex:%02X tar_bcd:%02X = %d\n",src_hex,tar_bcd,tar_bcd);


	tar_hex = BCDToChar(tar_bcd);
	printf("tar_bcd:%02X tar_hex:%02X\n",tar_bcd,tar_hex);
	
	us_tar_hex = BCDToShort(us_src_bcd);
	printf("us_src_bcd:%02X us_tar_hex:%02X\n",us_src_bcd,us_tar_hex);
	
	us_tar_bcd = ShortToBCD(us_tar_hex);
	printf("us_tar_hex:%02X us_tar_bcd:%02X = %d\n",us_tar_hex,us_tar_bcd,us_tar_bcd);
	
	ul_tar = StringToLong(str);
	printf("str:%s ul_tar:%d\n",str,ul_tar);
	
	return 0;
}

你可能感兴趣的:(C/C++)