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