以下代码使用四种方式实现了转换输出的功能:
1、运用“除2求余”的方法;
2、运用位运算的方式(不太明白为什么?),而且是倒序输出;
3、也是运用位运算,容易理解,但是输出零太多了:(
4、同上,输出做了处理:)
// L11_1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <math.h>
#include <iostream>
using namespace std;
void ToIntBinary(int nNum);//it is for integer;
void ToDecimalBinary(float nNum);//it is for decimal data;
int main(int argc, char* argv[])
{
//No1.using math
float fDecNum;
int nDecNum;
cout << "Please input a unsigned number:";
cin >>fDecNum;
cout <<"The Number "<<fDecNum<<" into binary is:";
//whether the number is unsigned?only integer?
if (fDecNum<0)
{
cout<<"-";
fDecNum=abs(fDecNum);
}
if (!(fDecNum-(int)fDecNum))
{
ToIntBinary(fDecNum);
}
else
{
ToIntBinary((int)fDecNum);
cout<<".";
ToDecimalBinary(fDecNum);
}
cout <<'/n';
//No.2 using Bit arithmetic
cout << "Please input a unsigned integer number:";
cin>>nDecNum;
cout <<"The Number "<<nDecNum<<" into binary is:";
while( nDecNum )
{
//change into binary (negative sequence)
cout<<(!(( nDecNum ^ (nDecNum-1))&(nDecNum-1)));
nDecNum = nDecNum >> 1;
}
cout<<endl;
//No.3 using Bit arithmetic
cout << "Please input a unsigned integer number:";
cin>>nDecNum;
cout <<"The Number "<<nDecNum<<" into binary is:";
//because integer have 4 bytes,so it have 32 bits;
//if int nMask=0x80000000,the result is not correct!
//if use "int",the highest position must be '0';
unsigned int unMask=0x80000000;//or int nMast=0x40000000;
int nBit;
//the result of following have more '0'
for(int i=0;i<32;i++)
{
nBit=(nDecNum & unMask)?1:0;
cout<<nBit;
//equal to nMask/2,move to next,getting the next mask word
unMask=unMask>>1;
}
cout<<endl;
//No.4 using Bit arithmetic
//the result of following looks better
cout << "Please input a unsigned integer number:";
cin>>nDecNum;
cout <<"The Number "<<nDecNum<<" into binary is:";
int nMask=0x40000000;
int nBitAnother;
while(nMask)
{
nBitAnother=(nDecNum & nMask)?1:0;
if (nBitAnother)
{
break;
}
nMask=nMask>>1;
}
while(nMask)
{
nBitAnother=(nDecNum & nMask)?1:0;
nMask=nMask>>1;
cout<<nBitAnother;
}
cout<<endl;
return 0;
}
void ToIntBinary(int nNum)
{
if(nNum==0)
{
cout <<"0";
}
else
if(nNum==1)
{
cout <<"1";
}
else
{
// ToIntBinary(nNum/2);//using recursion
ToIntBinary(nNum>>1);//same as the up;
cout << nNum%2;
}
}
void ToDecimalBinary(float nNum)
{
nNum=nNum-(int)nNum;
while(nNum)
{
nNum*=2;//equal to nNum=nNum<<1,but only with integer;
cout<<(int)nNum;
nNum=nNum-(int)nNum;
}
}