Java – How to multiply (and divide) BCD numbers by 10^x


I have a large (12 digit) BCD number, encoded in an array of 6 bytes – each nibble is one BCD digit. I need to multiply it by 10^x, where x can be positive or negative.

I know it can be done by shifting left or right by nibble instead of bit, but it's a horrible implementation – especially in Javacard, which is what I'm using. Is there a better way?

Best Solution

Shifting by nibbles is the most efficient way.

If performance is not your problem and you want to have the most readable version you may want to convert your BCD-number to a string and move the decimal point around.

In case you don't have a decimal point (e.g. your number is an integer) you can concat zeros if x > 0 or delete the last -x characters if x < 0.

Afterwards convert the string back to BCD. Watch out for overflows and and cases where you delete all characters and end up with an empty string.