Closed. This question does not meet Stack Overflow guidelines。它当前不接受答案。












想改善这个问题吗?更新问题,以便将其作为on-topic用于堆栈溢出。

6年前关闭。



Improve this question




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

最佳答案

干得好。我只是写了这个,并将其设为公共(public) Realm 。

它将无符号的bcd转换为无符号的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;
}

关于c++ - 在哪里可以找到免费或开源的C++库进行BCD数学运算? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6302195/

10-16 22:59