簡體   English   中英

將BCD字符串轉換為十進制

[英]Conver BCD Strings to Decimal

我正在尋找更好的方法來優化此功能以獲得更好的性能,並將其目標對准嵌入式設備。 我歡迎任何指點,建議謝謝

函數將字符串BCD轉換為十進制

int ConvertBCDToDecimal(const std::string& str, int splitLength)
{
    int NumSubstrings = str.length() / splitLength;
    std::vector<std::string> ret;
    int newvalue;

    for (auto i = 0; i < NumSubstrings; i++)
    {
        ret.push_back(str.substr(i * splitLength, splitLength));
    }

    // If there are leftover characters, create a shorter item at the end.
    if (str.length() % splitLength != 0)
    {
        ret.push_back(str.substr(splitLength * NumSubstrings));
    }

    string temp;

    for (int i=0; i<(int)ret.size(); i++)
     {
         temp +=ReverseBCDFormat(ret[i]);
     }

    return newvalue =std::stoi(temp);

}

string ReverseBCDFormat(string num)
{

    if( num == "0000")
    {
        return "0";
    }
    else if( num == "0001")
    {
        return "1";
    }
    else if( num == "0010")
    {
        return "2";
    }
    else if( num == "0011")
    {
        return "3";
    }
    else if( num == "0100")
    {
        return "4";
    }
    else if( num == "0101")
    {
        return "5";
    }
    else if( num == "0110")
    {
        return "6";
    }
    else if( num == "0111")
    {
        return "7";
    }
    else if( num == "1000")
    {
        return "8";
    }
    else if( num == "1001")
    {
        return "9";
    }
    else
    {
        return "0";

    }

}

更新這是我計划獲取的BCD值:: 0010000000000000小數結果2000

BCD是一種編碼十進制數字(兩個到一個字節)的方法。

例如0x12345678是十進制數字12345678的BCD表示形式。但是,這似乎不是您要處理的內容。 因此,當您說BCD時,我不確定您是指BCD。

至於代碼,您可以通過遍歷每個子字符串並直接計算值來大大提高速度。 至少,更改ReverseBCDFormat以返回整數而不是字符串,並即時計算字符串:

temp = temp * 10 + ReverseBCDFormat(...)

這樣的事情。

您所說的BCD實際上不是BCD。

有了它,您可以執行以下操作:

int ConvertBCDToDecimal(const std::string& str, int splitLength)
{
    int ret = 0;
    for (unsigned i = 0, n = unsigned(str.size()); i < n; )
    {
        int v = 0;
        for (unsigned j = 0; j < splitLength && i < n; ++j, ++i)
            v = 2*v + ('1' == str[i] ? 1 : 0); // or 2*v + (str[i]-'0')
        ret = 10*ret + v;
    }
    return ret;
}

擺脫所有無用的向量制作和字符串復制。 您不需要這些。

另外,我認為您的代碼在處理長度不是splitLength倍數的字符串時存在錯誤。 我認為您的代碼始終認為它們為零。 實際上,考慮到這一點,您的代碼將無法使用4以外的任何splitLength

順便說一句,如果您提供一些示例輸入以及它們的預期輸出,那么我將能夠根據您的示例實際驗證我的代碼(鑒於您對BCD的定義與大多數人的定義不同,您的代碼尚不完全清楚。)

在優化功能后,這是另一個變體:

int ConvertBCDToDecimal(const std::string& str) {
    unsigned int result = 0;
    const std::string::size_type l = str.length();
    for (std::string::size_type i = 0; i < l; i += 4)
        result = result * 10 + ((str[i] - '0') << 3) + ((str[i + 1] - '0') << 2) + ((str[i + 2] - '0') << 1) + (str[i + 3] - '0');
    return result;
}

注意:您不需要splitLength參數,因為您知道每個數字都是4個符號

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM