Binary-Coded Decimal conversion

K

kelvSYC

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)?
 
B

Brad BARCLAY

kelvSYC said:
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 mask = 0xF0000000;
int mult = 10000000;

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

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

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

return result;
} // end-method

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

Brad BARCLAY
 
B

Brad BARCLAY

Brad said:
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 :).

Brad BARCLAY
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top