简体   繁体   中英

Binary to Decimal in C++

if(input.is_open() && output.is_open())
{
    while(!input.eof())
    {
        char a=NULL;
        getline(input,line);
        while(!line.empty())
        {
        int num=0;
        string byte=line.substr(0,8);
        for(int i=0;i<byte.length();i++)
        {
            if(byte.at(i)==1)
            {
                num=num+pow(2,8-i);
            }
            else
            {
                num+=0;
            }
        }
        output << num << " ";
        line=line.substr(8);
        }

    }
}

I want to read from file which one line is 32 bit binary number take 8 bits from it and transform decimal. But above code give always 0.

A few things can be fixed, but the main problem is

if(byte.at(i)==1)

is comparing the character at i , a '1' (ASCII code 49) or a '0' (ASCII code 48), against the number 1. So if byte[i] is '1' , then 49 is compared against 1 and returns false.

Solution:

Compare character with character

if (byte.at(i) == '1')

In addition to what is said in the first answer, you need

num=num+pow(2,7-i);  // note 7 instead of 8.

This is assuming your input line looks like

10101010101010101010101010101010

and you want output like

170 170 170 170

If you are trying to do something else, then please clarify the question.

You may also want to heed the advice of those who commented on your question.

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