Velocity Reviews > Java > Binary-Coded Decimal conversion

# Binary-Coded Decimal conversion

kelvSYC
Guest
Posts: n/a

 12-30-2003
What is the best way to create a function that converts a BCD number
(stored in an int to make things simple) into a normal integer (ie.
int) value (or throw an exception if it cannot be done)?

--
I am only a mirage.

Guest
Posts: n/a

 12-30-2003
kelvSYC wrote:
> What is the best way to create a function that converts a BCD number
> (stored in an int to make things simple) into a normal integer (ie.
> int) value (or throw an exception if it cannot be done)?

A straight mask, bit-rotate, and multiply, for each digit, followed by
a summation of the results should suffice. You'll only need to throw an
exception if the number you get from the mask and rotate is outside the
acceptable BCD digit range (0 - 9). Presuming you're working with
packed BCD for values with a maximum of 4-decimal-digits in length, the
following should suffice:

public static int BCDtoInt(int packedVal)
throws NumberFormatException {
int result = 0;
int temp;
int rot = 28;
int mult = 10000000;

while (rot>=0) {
temp = (packedVal & mask) >> rot;

if (temp > 9) throw new NumberFormatException();
else result+=temp*mult;

mult/=10;
rot-=4;
} // end-while

return result;
} // end-method

Note that this can be optimized somewhat, but it should serve to
illustrate the algorithm. HTH!

--
=-=-=-=-=-=-=-=-=
From the OS/2 WARP v4.5 Desktop of Brad BARCLAY.
The jSyncManager Project: http://www.jsyncmanager.org

Guest
Posts: n/a

 12-30-2003

> Presuming you're working with
> packed BCD for values with a maximum of 4-decimal-digits in length...

Oops -- I _meant_ to say "8-decimal-digits in length", and not 4. The
code will happily handle 8 digit numbers -- my fingers simply hit the
wrong numeric key in the above fragment .

--
=-=-=-=-=-=-=-=-=
From the OS/2 WARP v4.5 Desktop of Brad BARCLAY.
The jSyncManager Project: http://www.jsyncmanager.org
