英锐恩单片机论坛,Microchip单片机,模拟器件,接口电路,麦肯单片机,单片机应用交流

标题: bcdbin转换的小程序 [打印本页]

作者: winnie    时间: 2009-4-7 10:53
标题: bcdbin转换的小程序
//===========================================================================
#include <pic.h>
//------------------------------------------------------------------------
unsigned int bcd_to_bin(unsigned char r[]) //65535以内: bcd->hex
{
unsigned char n,r0_s,r1_s,r2_s,hb_s,hb,lb;
unsigned int t;
hb=0;
lb=0;
for(n=16;n>0;)
     {
      r0_s=r[0];
      r1_s=r[1];
      r2_s=r[2];
      hb_s=hb;
      r[0]>>=1;
      r[1]>>=1;
      r[2]>>=1;
      hb>>=1;
      lb>>=1;
      if((r0_s&0x01)!=0) r[1]|=0x80;
      if((r1_s&0x01)!=0) r[2]|=0x80;
      if((r2_s&0x01)!=0) hb|=0x80;
      if((hb_s&0x01)!=0)lb|=0x80;      if(--n)
       {
        if((r[2]&0x08)!=0) r[2]-=0x03;
        if((r[1]&0x08)!=0) r[1]-=0x03;
        if((r[2]&0x80)!=0) r[2]-=0x30;
        if((r[1]&0x80)!=0) r[1]-=0x30;
       }
     }
t=((unsigned int)(hb<<8))|lb;
return(t);
}
//----------------------------------------------------------------------------
void adjust_bcd(unsigned char *pr)
{
unsigned char t;
t=*pr+0x03;
if((t&0x08)!=0) *pr=t;
t=*pr+0x30;
if((t&0x80)!=0) *pr=t;
}
//----
unsigned char * bin_to_bcd(unsigned int hlb)//65535以内: hex->bcd
{
unsigned char hb,lb,hb_s,lb_s,r1_s,r2_s,n;
unsigned char r[3]={0,0,0};
hb=hlb>>8;
lb=hlb;
for(n=16;n>0;)
    {
     hb_s=hb;
     lb_s=lb;
     r2_s=r[2];
     r1_s=r[1];
     lb<<=1;
     hb<<=1;
     r[2]<<=1;
     r[1]<<=1;
     r[0]<<=1;
     if((lb_s&0x80)!=0) hb|=0x01;
     if((hb_s&0x80)!=0) r[2]|=0x01;
     if((r2_s&0x80)!=0) r[1]|=0x01;
     if((r1_s&0x80)!=0) r[0]|=0x01;
     if(--n)
        {
          adjust_bcd(&r[2]);
          adjust_bcd(&r[1]);
          adjust_bcd(&r[0]);
        }
    }
return(r);
}
//-------------------------------------------------------------------------
main()
{
unsigned int t;
unsigned char r012[3]={0x01,0x023,0x45};
unsigned char *r;
t=bcd_to_bin(r012);
r=bin_to_bcd(0x3039);
r012[0]=*r;
r012[1]=*(r+1);
r012[2]=*(r+2);
while(1){;}
}
//===============================================================================




欢迎光临 英锐恩单片机论坛,Microchip单片机,模拟器件,接口电路,麦肯单片机,单片机应用交流 (http://enroobbs.com/) Powered by Discuz! X3.2