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

I have a large (12-bit) BCD number encoded in an array of 6 bytes - each chunk 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 going left or right on nibble, not bit, but it's a terrible implementation - especially in Javacard, and that's what I'm using. Is there a better way?

0


source to share


2 answers


Shifting by chunks is the most efficient way.

If performance isn't your concern and you want the most readable version, you can convert your BCD number to a string and move the decimal point around.



If you don't have a decimal point (for example, your number is an integer), you can specify zeros if x> 0, or remove the last -x characters if x <0.

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

+1


source


You don't need to use bit shift (although this is probably the most efficient way to do it).

For your 12 digit BCD number, assuming there is no overflow, suppose b [5] through b [0] contains your bytes from most significant to least significant, and mod is the modulus (remainder) operation and divs are integer divisions , the following pseudocode will be multiplied by 10:

for i = 5 to 1
    b[i] = (b[i] mod 16) * 16 + b[i-1] div 16
b[0] = (b[0] mod 16) * 16

      

To be honest, this is probably uglier than your bit shifting solution, but as long as you encapsulate any of them into a function, it doesn't really matter.



I suggest having a function line by line:

BcdArray mult10 (BcdArray ba, int shiftAmt);

      

which would return a modified array applying that cardinality of 10.

Any even power of ten is a simple copy of the bytes (since two nybbles are a byte), while only odd powers of ten need a complex bit-shift or remainder / division code.

0


source







All Articles