void convertBinaryToDecimal(std::string BinarySrc, std::string& DecimalDest)
{
}我需要将字符串二进制长度128位转换为字符串十进制数
发布于 2020-05-29 16:55:38
算法很简单:
使用初始化为0;
v = v + v + bit;
v生成十进制数字:digit = '0' + v % 10,而(v /= 10) != 0.
这应该很容易转换成代码。
发布于 2020-05-29 18:31:43
对于用户chqrlie给出的答案,我会立即问,我们现在哪里有128位无符号整数变量,即使是这样,我们将如何处理500位字符串?因此,这种方法当然不会奏效。
这里我们需要的是二进制数的整数除法。然后,我们将执行与小数相同的操作。整数除以10,余数就是我们感兴趣的数字。
下面显示的功能适用于包含二进制数的任意长字符串。也可以使用其他数字基数
请参阅:
编辑
根据用户chux的良好观察进行了更新
#include <iostream>
#include <string>
#include <algorithm>
int main() {
// This is the input number
std::string binAsString{ "101010" };
// Show orignial string to user
std::cout << "\n\n" << binAsString;
// Here we will store the resulting output
std::string result{};
// The conversion will also work for other number bases
// For base > 10 you need to adapt the creation of the digit at the bottom
constexpr unsigned int numberBase{ 10 };
// So, we will perfrom an integer division by 10, until the number is 0
do {
// The remainder is the digit that we are interested in
unsigned int remainder{};
// Temporary result of integer division
std::string dividedNumberAsString{};
// Do the division
for (const char bit : binAsString) {
// Calculate the remainder
remainder = remainder * 2 + (bit - '0');
// If we have a overflow (e.g. number is bigger than 10)
if (remainder >= numberBase) {
// Handle overflow
remainder -= numberBase;
// Add character 1 to the "devidedString"
dividedNumberAsString += "1";
}
else {
dividedNumberAsString += "0";
}
}
// Now "dividedNumberAsString" as string is the result of the devision by e.g. 10 in binary form
binAsString = dividedNumberAsString;
// The remainder is the number that we are interested in
result.insert(0, 1, '0' + remainder);
// Continue the loop with the new binary string
} while (std::count(binAsString.begin(), binAsString.end(), '1'));
// Show result
std::cout << " -->\n" << result << "\n\n";
return 0;
}发布于 2020-05-29 19:54:17
我想我可以给你一点提示,而不是直接提供解决方案。
取长二进制数,并将其一分为二(或四分之一,或其他任何值)。
跟踪其中哪些是二进制数的上限范围,哪些是二进制数的下限范围。
计算下限值域和上限值域的真值,然后将它们相加。
https://stackoverflow.com/questions/62081950
复制相似问题