winnie 发表于 2009-4-7 10:53:04

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;
      r1_s=r;
      r2_s=r;
      hb_s=hb;
      r>>=1;
      r>>=1;
      r>>=1;
      hb>>=1;
      lb>>=1;
      if((r0_s&0x01)!=0) r|=0x80;
      if((r1_s&0x01)!=0) r|=0x80;
      if((r2_s&0x01)!=0) hb|=0x80;
      if((hb_s&0x01)!=0)lb|=0x80;      if(--n)
       {
      if((r&0x08)!=0) r-=0x03;
      if((r&0x08)!=0) r-=0x03;
      if((r&0x80)!=0) r-=0x30;
      if((r&0x80)!=0) r-=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={0,0,0};
hb=hlb>>8;
lb=hlb;
for(n=16;n>0;)
    {
   hb_s=hb;
   lb_s=lb;
   r2_s=r;
   r1_s=r;
   lb<<=1;
   hb<<=1;
   r<<=1;
   r<<=1;
   r<<=1;
   if((lb_s&0x80)!=0) hb|=0x01;
   if((hb_s&0x80)!=0) r|=0x01;
   if((r2_s&0x80)!=0) r|=0x01;
   if((r1_s&0x80)!=0) r|=0x01;
   if(--n)
      {
          adjust_bcd(&r);
          adjust_bcd(&r);
          adjust_bcd(&r);
      }
    }
return(r);
}
//-------------------------------------------------------------------------
main()
{
unsigned int t;
unsigned char r012={0x01,0x023,0x45};
unsigned char *r;
t=bcd_to_bin(r012);
r=bin_to_bcd(0x3039);
r012=*r;
r012=*(r+1);
r012=*(r+2);
while(1){;}
}
//===============================================================================
页: [1]
查看完整版本: bcdbin转换的小程序