gpt4 book ai didi

c++ - 将 BCD 字符串转换为十进制

转载 作者:行者123 更新时间:2023-11-28 05:48:45 26 4
gpt4 key购买 nike

我正在寻找更好的方法来优化此功能以获得更好的性能,加快其针对嵌入式设备的目标。我欢迎任何指点,建议谢谢

函数将字符串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(...)

类似的东西。

关于c++ - 将 BCD 字符串转换为十进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35708779/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com