BCD数学を行うための無料またはオープンソースのC ++ライブラリはどこにありますか? [閉まっている

StackOverflow https://stackoverflow.com/questions/6302195

  •  25-10-2019
  •  | 
  •  

質問

無料またはオープンソースのC ++ライブラリはどこにありますか バイナリコーディングされた小数 算数?

役に立ちましたか?

解決

どうぞ。私はこれを書いたばかりで、パブリックドメインにしています。

署名されていないBCDを署名のないINTに変換し、その逆にします。 bcd2i()を使用して、bcdsを符号なしのintに変換し、必要な数学を実行し、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;
}

他のヒント

私の知る限り、変換エラーは常に受け入れられるとは限りません。エラーを回避できないため、BCD計算は必須である場合があります。たとえば、XBCD_MATHは、完全に機能するBCDフローティングポイントライブラリです。

数学は数学です - ベース2、ベース10、またはベース16に追加または乗算することは問題ではありません。答えは常に同じです。

あなたの入力と出力がどのようにコーディングされるかはわかりませんが、必要なのはBCDから整数に変換され、通常のように数学を行い、最後に整数からBCDに再変換します。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top