Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.
Posted
Updated 28-Nov-15 12:52pm
v2

1 solution

The best way to convert binary string to number are the stoXX functions.
http://www.cplusplus.com/reference/string/stoi/[^]
So:
C++
#include <iostream>
#include <string>

int main()
{
	const std::string bitstr = "00001111";
	int intval = std::stoi(bitstr, 0, 2);
	std::cout << intval << std::endl;

	return 0;
}

After that just use your debugger to make sure the input string contains the value you think it should.

If you are using C++11 there is bitset.
http://www.cplusplus.com/reference/bitset/bitset/[^]
C++
#include <iostream>
#include <string>
#include <bitset>

int main()
{
	const std::string bitstr = "00001111";
	int intval = static_cast<int>(std::bitset<8>(bitstr).to_ulong());
	std::cout << intval << std::endl;

	return 0;
}
 
Share this answer
 
v5
Comments
Sergey Alexandrovich Kryukov 29-Nov-15 3:58am    
Sure, a 5.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900