Question

Edit:

I have (test file in ascii) the following record in ascii: "000000000.00"
I need to output it ISO upon parsing it's counter part in BCD (the other test file in bcd/ebcdic).
I believe it takes 6 char in BCD and 11 in ascii.
So my need was something that could convert it back and forth.
First I thought of taking each chars, feed it to a convert function and convert it back hence my messed up question.

I hope i'm more clear.

Yain

Was it helpful?

Solution

Dr. Peter Below (of Team B) donated these in the old Borland Delphi newsgroups a few years ago:

// NO NEGATIVE NUMBERS either direction.

// BCD to Integer
function BCDToInteger(Value: Integer): Integer;
begin
  Result := (Value and $F);
  Result := Result + (((Value shr 4) and $F) * 10);
  Result := Result + (((Value shr 8) and $F) * 100);
  Result := Result + (((Value shr 16) and $F) * 1000);
end;

// Integer to BCD
function IntegerToBCD(Value: Integer): Integer;
begin
  Result :=                   Value div 1000 mod 10;
  Result := (Result shl 4) or Value div  100 mod 10;
  Result := (Result shl 4) or Value div   10 mod 10;
  Result := (Result shl 4) or Value          mod 10;
end;

OTHER TIPS

As you may know, the ASCII codes of the numerals 0 through 9 are 48 through 57. Thus, if you convert each character in turn to its ASCII equivalent and subtract 48, you get its numerical value. Then you multiply by ten, and add the next number. In pseudo code (sorry, not a delphi guy):

def bcdToInt( string ):
  val = 0

  for each ch in string:
    val = 10 * val + ascii(ch) - 48; 

  return val; 

If your "string" in fact contains "true BCD values" (that is, numbers from 0 to 9, rather than their ASCII equivalent 48 to 57), then don't subtract the 48 in the above code. Finally, if two BCD values are tucked into a single byte, you would access successive members with a bitwise AND with 0x0F (15). But in that case, Ken White's solution is clearly more helpful. I hope this is enough to get you going.

functions below work for 8 digit hexadecimal and BCD values.

function BCDToInteger(Value: DWORD): Integer;
const Multipliers:array[1..8] of Integer=(1, 10, 100, 1000, 10000, 100000, 1000000, 10000000);
var j:Integer;
begin
 Result:=0;
 for j:=1 to 8 do //8 digits
 Result:=Result+(((Value shr ((j-1)*4)) and $0F) * Multipliers[j]);
end;//BCDToInteger

function IntegerToBCD(Value: DWORD): Integer;
const Dividers:array[1..8] of Integer=(1, 10, 100, 1000, 10000, 100000, 1000000, 10000000);
var j:Integer;
begin
 Result:=0;
 for j:=8 downto 1 do //8 digits
 Result:=(Result shl 4) or ((Value div Dividers[j]) mod 10);
end;//IntegerToBCD
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top