我在哪里可以找到一个免费或开源的C++库来做BCD数学

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

本文关键字:C++ 开源 数学 BCD 免费 一个 在哪里      更新时间:2023-10-16

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

开始吧。我刚刚写了这篇文章,并将其公开。

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

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

数学就是数学——在2、10或16进制中进行加法或乘法都无关紧要:答案总是一样的。

我不知道你的输入和输出是如何编码的,但你所需要的就是从BCD转换成整数,像往常一样计算,最后再从整数转换成BCD。