我在哪里可以找到一个免费或开源的C ++库来进行BCD数学运算?

时间:2011-06-10 05:08:01

标签: c++ open-source bcd

我在哪里可以找到一个免费或开源的C ++库来进行Binary Coded Decimal数学?

3 个答案:

答案 0 :(得分:4)

你走了。我刚刚写了这篇文章,并将其作为公共领域。

它将无符号bcd转换为unsigned int,反之亦然。使用bcd2i()将您的BCD转换为无符号整数,执行您需要的任何数学运算,然后使用i2bcd()将数字恢复为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;
}

答案 1 :(得分:2)

据我所知,转换错误并不总是可以接受的。由于无法避免错误,BCD计算有时是必须的。例如,XBCD_Math是一个功能齐全的BCD浮点库。

答案 2 :(得分:0)

数学是数学 - 你在基数2,基数10或基数16中加或加是无关紧要的:答案总是一样的。

我不知道您的输入和输出将如何编码,但您应该只需要将BCD转换为整数,就像通常那样进行数学运算,最后从整数重新转换为BCD。