lundi 29 février 2016

Conver BCD Strings to Decimal

I am looking for better ways to optimize this function for better performance, speed its targeted towards embedded device. i welcome any pointers, suggestion thanks

function converts string BCD to Decimal

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";

    }

}

Aucun commentaire:

Enregistrer un commentaire