-1
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.

Lucas
  • 170
  • 3
  • 14
  • Off topic: `while(!input.eof())` is a bad idea. Read more here: http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – user4581301 Nov 29 '15 at 01:16
  • Off topic: untested file read: `getline(input,line);` you have no idea whether or not a line was read. – user4581301 Nov 29 '15 at 01:18
  • 1
    Off topic: `pow` is overkill here and brutally slow. You can use bit shifting. `num=num +(1 << (8-i));` will set the (8-i)th bit and add it to the current value of num. – user4581301 Nov 29 '15 at 01:24
  • When i debug it, it takes corret line ok als it takes 8 bit from that line, but it cant enter if statement ? – Lucas Nov 29 '15 at 01:24
  • Apologies. `num=num +(1 << (8-i));` should be `num=num +(1 << (7-i));` – user4581301 Nov 29 '15 at 01:39

2 Answers2

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')
user4581301
  • 33,082
  • 7
  • 33
  • 54
0

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.

Anatoli P
  • 4,791
  • 1
  • 18
  • 22