Pergunta

Where can I find a free or open source C++ library to do Binary Coded Decimal math?

Foi útil?

Solução

Here you go. I just wrote this, and am making it public domain.

It converts an unsigned bcd to an unsigned int and vice-versa. Use bcd2i() to convert your BCDs to unsigned ints, do whatever math you need, then use i2bcd() to bring the numbers back to BCD.

unsigned int bcd2i(unsigned int bcd) {
    unsigned int decimalMultiplier = 1;
    unsigned int digit;
    unsigned int i = 0;
    while (bcd > 0) {
        digit = bcd & 0xF;
        i += digit * decimalMultiplier;
        decimalMultiplier *= 10;
        bcd >>= 4;
    }
    return i;
}

unsigned int i2bcd(unsigned int i) {
    unsigned int binaryShift = 0;  
    unsigned int digit;
    unsigned int bcd = 0;
    while (i > 0) {
        digit = i % 10;
        bcd += (digit << binaryShift);
        binaryShift += 4;
        i /= 10;
    }
    return bcd;
}
// Thanks to EmbeddedGuy for bug fix: changed init value to 0 from 1 


#include <iostream>
using namespace std;

int main() {
int tests[] = {81986, 3740, 103141, 27616, 1038, 
               56975, 38083, 26722, 72358, 
                2017, 34259};

int testCount = sizeof(tests)/sizeof(tests[0]);

cout << "Testing bcd2i(i2bcd(test)) on 10 cases" << endl;
for (int testIndex=0; testIndex<testCount; testIndex++) {
    int bcd = i2bcd(tests[testIndex]);
    int i = bcd2i(bcd);
    if (i != tests[testIndex]) {
        cout << "Test failed: " << tests[testIndex] << " >> " << bcd << " >> " << i << endl;
        return 1;
    }
}
cout << "Test passed" << endl;
return 0;
}

Outras dicas

As far as I know, conversion errors are not always acceptable. As errors can't be avoided, BCD computations are sometimes a must. XBCD_Math, for example, is a fully featured BCD floating point library.

Math is math - it doesn't matter is you add or multiply in base 2, in base 10 or in base 16: the answer is always the same.

I don't know how your input and output would be coded, but all you should need is convert from BCD to integer, do the math just like you normally would, and at the end re-convert from integer to BCD.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top