十进制数转换为二进制数的两种方法

下面代码仅供本人复习所用,实用性N低,各位飘过吧~~哈哈:>

//
// 十进制转二进制. 
// 

#include <cstdlib>
#include <iostream>
#include <vector>

//
// 使用 unsigned long long 类型数值来表示二进制数,
// 由于这样表示的二进制数位数有限,顾输入参数为 unsigned short 类型. 
//
unsigned long long toBinary(unsigned short decimal) 
{
	long long binary = 0;
	long long carry = 1; 
	while (0 < decimal) {
		binary += decimal % 2 ? carry : 0;
		carry *= 10;
		decimal /= 2;
	}
	return binary; 
}

//
// 使用向量保存二进制数字符串. 
//
void toBinary_vector(unsigned long decimal, std::vector<char> &binary)
{
	while (0 < decimal) {
		binary.push_back(decimal % 2 + '0');
		decimal /= 2;
	}
}

//
// 测试. 
// 
int main(void)
{
	std::cout << "Input decimal number: "; 
	
	unsigned short decimal;
	while (!(std::cin >> decimal)) {
		std::cin.sync();
		std::cin.clear();
		std::cout << "Input wrong, please input again: "; 
	}
	std::cout << "Binary: " << toBinary(decimal) << std::endl; 
	
	std::vector<char> binary;
	
	toBinary_vector(decimal, binary);
	std::vector<char>::iterator beg = binary.begin();
	std::vector<char>::iterator end = binary.end();
	std::cout << "Binary: ";
	while (beg != end--) {
		std::cout << *end;
	}
	std::cout << std::endl; 
 
	return EXIT_SUCCESS;
}
posted @ 2011-06-01 15:45  Atypiape2  阅读(957)  评论(0编辑  收藏  举报