繁体   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