BCD码与十进制的相互转换
BCD码是用每四位代替一位十进制数(0 到 9 的某一位数) 例如:0x25 就代表25 十六进制的每位转换成二进制代表四个位。
下面是bcd转char short int long c语言程序
//**********************************************************************
// turn byte data to BCD data
//**********************************************************************
unsigned char Byte_BCD(unsigned char Data)
{ if (Data>=99)
return 0x99;
return( Data/10*0x10 + Data%10 ); }
//**********************************************************************
// turn word data to BCD data
//**********************************************************************
void Word_BCD(unsigned char *Ptr, unsigned int Data)
{
if (Data>=9999)
{ *(Ptr+1) = 0x99;
*Ptr = 0x99;
return; }
*(Ptr+1) = Byte_BCD( (unsigned char)(Data/100) );
*Ptr = Byte_BCD( (unsigned char)(Data%100) );
}
//**********************************************************************
// turn long data to BCD3 data
//**********************************************************************
void Long_BCD3(unsigned char *Ptr, unsigned long Data)
{
if (Data>=999999)
{ *(Ptr+2) = 0x99;
*(Ptr+1) = 0x99;
*Ptr = 0x99;
return; }
*(Ptr+2) = Data/100000*0x10 + Data/10000;
Word_BCD(Ptr, (unsigned int)(Data%10000));
}
//**********************************************************************
// turn long data to BCD4 data
//**********************************************************************
void Long_BCD4(unsigned char *Ptr, unsigned long Data)
{
if (Data>=99999999)
{ *(Ptr+3) = 0x99;
*(Ptr+2) = 0x99;
*(Ptr+1) = 0x99;
*Ptr = 0x99;
return; }
Word_BCD(Ptr+2, Data/10000);
Word_BCD(Ptr, Data%10000);
}
//**********************************************************************
// turn BCD data to byte data
//**********************************************************************
unsigned char BCD_Byte(unsigned char Data)
{
return(((Data>>4)&0x0f)*10+(Data&0x0f));
}
//**********************************************************************
// turn BCD2 data to word data
//**********************************************************************
unsigned int BCD2_Word(unsigned char *Ptr)
{
return( (int)BCD_Byte(*Ptr)+
(int)BCD_Byte(*(Ptr+1))*100 );
}
//**********************************************************************
// turn BCD3 data to word data
//**********************************************************************
unsigned long BCD3_Long(unsigned char *Ptr)
{
return( (long)BCD_Byte(*Ptr)+
(long)BCD_Byte(*(Ptr+1))*100+
(long)BCD_Byte(*(Ptr+2))*10000 );
}
//**********************************************************************
// turn BCD4 data to word data
//**********************************************************************
unsigned long BCD4_Long(unsigned char *Ptr)
{
return( (long)BCD_Byte(*Ptr)+
(long)BCD_Byte(*(Ptr+1))*100+
(long)BCD_Byte(*(Ptr+2))*10000+
(long)BCD_Byte(*(Ptr+3))*1000000 );
}
posted on 2013-12-10 13:37 Darren715 阅读(6585) 评论(0) 编辑 收藏 举报