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.

Brad BARCLAY
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 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

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

Brad BARCLAY
Guest
Posts: n/a

 12-30-2003
Brad BARCLAY wrote:

> 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

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

 Thread Tools

 Posting Rules You may not post new threads You may not post replies You may not post attachments You may not edit your posts BB code is On Smilies are On [IMG] code is On HTML code is OffTrackbacks are On Pingbacks are On Refbacks are Off Forum Rules

 Similar Threads Thread Thread Starter Forum Replies Last Post python@lists.fastmail.net Python 0 07-19-2010 12:32 PM valpa Python 11 03-24-2009 07:11 AM Vitaliy Python 1 05-29-2008 10:36 AM Gilbert Fine Python 8 08-01-2007 01:58 AM Ven C++ 3 08-01-2006 03:56 PM

Advertisments