2

在哪里可以找到免费或开源 C++ 库来进行二进制编码十进制数学?

4

3 回答 3

4

干得好。我刚刚写了这个,并将其设为公共领域。

它将 unsigned 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;
}
于 2011-06-10T05:25:32.833 回答
2

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

于 2013-01-31T17:47:48.623 回答
0

数学就是数学——以 2 为底、以 10 为底还是以 16 为底的加法或乘法并不重要:答案总是相同的。

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

于 2011-06-10T05:20:38.717 回答