C: Decimal to BCD

From FSDeveloper Wiki
Revision as of 09:43, 13 June 2012 by N4gix (talk | contribs)
Jump to navigationJump to search

C: BCD to Decimal and Decimal to BCD

This scheme was supplied by Arne Bartels which allows BCD conversion in both directions. Add the following to the master source file:-

#include <math.h>
#define Bcd2Dec(BcdNum) HornerScheme(BcdNum,0x10,10)
#define Dec2Bcd(DecNum) HornerScheme(DecNum,10,0x10)

UINT32 HornerScheme(UINT32 Num,UINT32 Divider,UINT32 Factor)
{
   UINT32 Remainder=0,Quotient=0,Result=0;
   Remainder=Num%Divider;
   Quotient=Num/Divider;
   if(!(Quotient==0&&Remainder==0))
   Result+=HornerScheme(Quotient,Divider,Factor)*Factor+Remainder;
   return Result;
}

Then for each sub-gauge that requires a BCD conversion use the following syntax:-

Bcd2Dec(bcd_number) for BCD to decimal and
Dec2Bcd(dec_number) for decimal to BCD conversions.