Subject: Binary Coded Decimals 61. ***** Q: What are Binary Coded Decimals? How to convert them? A: Let us look at full integers only and skip the even more difficult question of BCD reals and BCD operations. Decimal Hexa BCD 1 $1 1 : $9 9 10 $A .. : : : 12 $C .. : : : 16 $10 10 17 $11 11 18 $12 12 : : : Consider the last value, that is BCD presentation of 12. The corresponding hexadecimal is $12 (not $C as in normal decimal to hexadecimal conversion). The crucial question is how to convert 12BCD to $12 (or its normal decimal equivalent 18). Here is my sample code: type BCDType = array [0..7] of char; {} procedure StrToBCD (s : string; var b : BCDType); var i, p : byte; begin FillChar(b, SizeOf(b), '0'); p := Length (s); if p > 8 then exit; for i := p downto 1 do b[p-i] := s[i]; end; (* strtobcd *) {} function BCDtoDec (b : BCDType; var ok : boolean) : longint; const Digit : array [0..9] of char = '0123456789'; var i, k : byte; y, d : longint; begin y := 0; d := 1; ok := false; for i := 0 to 7 do begin k := Pos (b[i], Digit); if k = 0 then exit; y := y + (k-1) * d; if i < 7 then d := 16 * d; end; { for } ok := true; BCDtoDec := y; end; (* bcdtodec *) {} {} procedure TEST; var i : byte; b : BCDType; x : longint; ok : boolean; s : string; begin s := '12'; StrToBCD (s, b); write ('The BCD value : '); for i := 7 downto 0 do write (b[i], ' '); writeln; x := BCDtoDec (b, ok); if ok then writeln ('is ', x, ' as an ordinary decimal') else writeln ('Error in BCD'); end; (* test *) {} begin TEST; end. Next we can ask, what if the BCD value is given as an integer. Simple, first convert the integer into a string. For example in the procedure TEST put Str (12, s); Finally, what about converting an ordinary decimal to the corresponding BCD but given also as a decimal variable. For example 18 --> 12? function LHEXFN (decimal : longint) : string; const hexDigit : array [0..15] of char = '0123456789ABCDEF'; var i : byte; s : string; begin FillChar (s, SizeOf(s), ' '); s[0] := chr(8); for i := 0 to 7 do s[8-i] := HexDigit[(decimal shr (4*i)) and $0F]; lhexfn := s; end; (* lhexfn *) {} function DecToBCD (x : longint; var ok : boolean) : longint; const Digit : array [0..9] of char = '0123456789'; var hexStr : string; var i, k : byte; y, d : longint; begin hexStr := LHEXFN(x); y := 0; d := 1; ok := false; for i := 7 downto 0 do begin k := Pos (hexStr[i+1], Digit); if k = 0 then exit; y := y + (k-1) * d; if i > 0 then d := 10 * d; end; { for } ok := true; DecToBCD := y; end; (* dectobcd *) {} procedure TEST2; var i : byte; x10 : longint; xBCD : longint; ok : boolean; begin x10 := 18; writeln ('The ordinary decimal value : ', x10); xBCD := DecToBCD (x10, ok); if ok then writeln ('is ', xBCD, ' as a binary coded decimal') else writeln ('Error in BCD'); end; (* test2 *) {} begin TEST; end. --------------------------------------------------------------------