Translation from binary into decimal numbers in C++

后端 未结 3 1799
轻奢々
轻奢々 2021-01-26 19:30

I tried to build a function that calculates a binary number stored in a string into a decimal number stored in a long long. I\'m thinking that my code should work b

相关标签:
3条回答
  • 2021-01-26 19:37

    c++ way

    #include <string>
    #include <math.h>
    #include <iostream>
    
    
    using namespace std;
    int main() {
        std::string stringNumber = "101110111";   
        long long result = 0;
    
        uint string_length = stringNumber.length();
    
        for(int i = 0; i <string_length; i++) {
          if(stringNumber[i]=='1')
          {
            long pose_value = pow(2, string_length-1-i);        
            result += pose_value;
          }       
            
        }
        std::cout << result << std::endl;
    }
    
    0 讨论(0)
  • 2021-01-26 19:40

    You're forgetting to convert your digits into integers. Plus you really don't need to use C strings.

    Here's a better version of the code

    int main() {
        std::string stringNumber = "101110111";
    
        int subtrahend = 1;
        int potency = 0;
        long long result = 0;
    
        for(int i = 0; i < stringNumber.size(); i++) {
            result += pow(2*(stringNumber[stringNumber.size() - subtrahend] - '0'), potency);
            subtrahend++;
            potency++;
            std::cout << result << std::endl;
        }
    }
    

    Subtracting '0' from the string digits converts the digit into an integer.

    Now for extra credit write a version that doesn't use pow (hint: potency *= 2; instead of potency++;)

    0 讨论(0)
  • 2021-01-26 19:44

    '1' != 1 as mentioned in the comments by @churill. '1' == 49. If you are on linux type man ascii in terminal to get the ascii table.

    Try this, it is the same code. I just used the stringNumber directly instead of using const char* to it. And I subtracted '0' from the current index. '0' == 48, so if you subtract it, you get the actual 1 or 0 integer value:

        auto sz = stringNumber.size();
    
        for(int i = 0; i < sz; i++) {
            result += pow((stringNumber[sz - subtrahend] - '0') * 2, potency);
            subtrahend++;
            potency++;
            std::cout << result << std::endl;
        }
    
    

    Moreover, use the methods provided by std::string like .size() instead of doing strlen() on every iteration. Much faster.


    In a production environment, I would highly recommend using std::bitset instead of rolling your own solution:

        std::string stringNumber = "1111";
        std::bitset<64> bits(stringNumber);
        bits.to_ulong();
    
    0 讨论(0)
提交回复
热议问题