二进制到十进制C ++ [英] Binary to Decimal C++

查看:76
本文介绍了二进制到十进制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);
			}

		}
	}



我想从文件中读取哪一行是32位二进制数取8来自它的位和转换小数。但上面的代码始终为0.


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.

推荐答案

将二进制字符串转换为数字的最佳方法是stoXX函数。

http://www.cplusplus.com/reference/string/stoi/ [ ^ ]

所以:

The best way to convert binary string to number are the stoXX functions.
http://www.cplusplus.com/reference/string/stoi/[^]
So:
#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;
}



之后只需使用调试器确保输入字符串包含您认为应该的值。



如果您使用的是C ++ 11,则有bitset。

http ://www.cplusplus.com/reference/bitset/bitset/ [ ^ ]


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/[^]

#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;
}


这篇关于二进制到十进制C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆