Ask the Expert

Converting a decimal to BCD in Java

Using Java, I need to convert a decimal to a packed BCD and back (packed BCD to Decimal), if possible, signed or unsigned. Can you help? I am hoping that there might be some open source software out here that I could work from. Would you know of any available open source that does this?

    Requires Free Membership to View

My God, someone asking about BCD. Next it'll be how to solve polynomials with VAX microcode. It looks like there's no free code anywhere, as far as I can tell, except for a small example in C called Jon's BCD Clock. It does unsigned-to-BCD only.

Scratching my head, it sounds pretty simple though. A DECIMAL type is probably implemented (for you) as a BigDecimal. You can toString() that type. Once you've got a string, you're most of the way to BCD. Take each character, subtract "0" and stuff the result in a byte of a byte array. For signed numbers, that's a trickier proposition and depends on the packed format; I don't recall any signed BCD formats offhand.

This was first published in January 2005

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: