首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在c++中将二进制字符串128位转换为十进制字符串?

如何在c++中将二进制字符串128位转换为十进制字符串?
EN

Stack Overflow用户
提问于 2020-05-29 16:41:39
回答 3查看 535关注 0票数 0
代码语言:javascript
复制
void convertBinaryToDecimal(std::string BinarySrc, std::string& DecimalDest)
{

}

我需要将字符串二进制长度128位转换为字符串十进制数

EN

回答 3

Stack Overflow用户

发布于 2020-05-29 16:55:38

算法很简单:

使用初始化为0;

  • for从v = v + v + bit;

  • then读取的每一位的128位无符号变量v生成十进制数字:digit = '0' + v % 10,而(v /= 10) != 0.

  • finally,反转十进制数字字符串。

这应该很容易转换成代码。

票数 2
EN

Stack Overflow用户

发布于 2020-05-29 18:31:43

对于用户chqrlie给出的答案,我会立即问,我们现在哪里有128位无符号整数变量,即使是这样,我们将如何处理500位字符串?因此,这种方法当然不会奏效。

这里我们需要的是二进制数的整数除法。然后,我们将执行与小数相同的操作。整数除以10,余数就是我们感兴趣的数字。

下面显示的功能适用于包含二进制数的任意长字符串。也可以使用其他数字基数

请参阅:

编辑

根据用户chux的良好观察进行了更新

代码语言:javascript
复制
#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;
}
票数 2
EN

Stack Overflow用户

发布于 2020-05-29 19:54:17

我想我可以给你一点提示,而不是直接提供解决方案。

取长二进制数,并将其一分为二(或四分之一,或其他任何值)。

跟踪其中哪些是二进制数的上限范围,哪些是二进制数的下限范围。

计算下限值域和上限值域的真值,然后将它们相加。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62081950

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档