简体   繁体   中英

Count the number of digits in a Binary

For this program, I will input a Binary number and it will convert into a decimal number. At the end I wanted to return the number of digits in the Binary number that I had input. For example, 1001 - 4 Binary digits.The output of the digits of Binary number is always 0. Should I use size_type to do it?

#include<iostream>
#include<string>
#include<bitset>
#include<limits>
#include<algorithm>

using namespace std;
int multiply(int x);

int multiply(int x)
{
    if (x == 0)
    {
        return 1;
    }

    if (x == 1)
    {
        return 2;
    }

    else
    {
        return 2 * multiply(x - 1);
    }
}

int count_set_bit(int n) 
{
    int count = 0;
    while (n != 0) 
    {
        if (n & 1 == 1) 
        {
            count++;
        }
        n = n >> 1; 
    }
    return count;
}

int main()
{
    string binary;

    cout << "\n\tDualzahlen : ";
    cin >> binary;

    reverse(binary.begin(), binary.end());
    int sum = 0;
    int size = binary.size();
    for (int x = 0; x < size; x++)
    {
        if (binary[x] == '1')
        {
            sum = sum + multiply(x);
        }
    }
    cout << "\tDezimal : " << sum << endl;

    int n{};
    cout << "\tAnzahl der Stelle : " << count_set_bit(n) << endl;
}

It looks like you are on the right track for unsigned integers. Signed integers in a multiply are generally converted to positive with a saved result sign.

You can save some time with a bit data solution, as value testing is not cost free plus 'and' has no carry delay. Of course, some CPUs can ++ faster than += 1, but hopefully the compiler knows how to use that:

int bits( unsigned long num ){
    retVal = 0 ;

    while ( num ){
        retVal += ( num & 1 );
        num >>= 1 ;
    }

    return retVal ;
}

I recall the H-4201 multiplied 2 bits at a time, using maybe shift, maybe add, maybe carry/borrow, so 0 was no add, 1 was add, 2 was shift and add, 3 was carry/borrow add (4 - 1). That was before IC multiply got buried in circuits and ROMs: :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM